我对 rust 很陌生,对 bevy 也很陌生。我意识到这是早期的日子,并且非常喜欢 bevy,但坦率地说,我发现示例和文档有点缺乏。
我以/examples/ui/button.rs
为起点。我想添加一堆按钮,而不仅仅是一个。
我正在寻找一种方法来区分单击了哪个按钮。
我意识到我可以为每个按钮添加一个系统,但这在任何语言中都不是正确的方法。
所以,我开始添加标记(就像 bevy-cheatsheet 建议的那样)。
commands
.spawn(ButtonComponents { /* cut for brevity */ })
.with_children(|parent| {
parent
.spawn(TextComponents { /* cut for brevity */ })
.with(Marker1);
});
但是我该如何去检查一个按钮是用什么标记生成的呢?
fn button_system(
button_materials: Res<ButtonMaterials>,
mut interaction_query: Query<(
&Button,
Mutated<Interaction>,
&mut Handle<ColorMaterial>,
&Children,
)>,
text_query: Query<&mut Text>,
) {
for (_button, interaction, mut material, children) in &mut interaction_query.iter() {
let mut text = text_query.get_mut::<Text>(children[0]).unwrap();
match *interaction {
Interaction::Clicked => {
// This obviously doesn't work, just to illustrate what I'm looking for.
match text.spawned_with {
Marker1 => doSomething(),
Marker2 => doBarrelRoll(),
_ => unreachable!()
}
}
Interaction::Hovered => {
text.value = "Hover".to_string();
*material = button_materials.hovered.clone();
}
Interaction::None => {
text.value = "Button".to_string();
*material = button_materials.normal.clone();
}
}
}
}
欢迎任何提示,谢谢!
编辑:现在我很困惑,因为这实际上适用于按钮 1,(但按钮 2 崩溃):
Interaction::Clicked => {
let marker = text_query.get::<_>(children[0]).unwrap();
match *marker {
Marker1 => println!("marker 1"),
_ => unreachable!(),
}
}
但这甚至没有建立:
let marker = text_query.get::<_>(children[0]).unwrap();
match *marker {
Marker1 => println!("marker 1"),
Marker2 => println!("marker 2"),
_ => unreachable!(),
}
这是错误:
| expected struct `Marker1`, found struct `Marker2`
| `Marker2` is interpreted as a unit struct, not a new binding
| help: introduce a new binding instead: `other_marker2`