Best way to expose a getter/setter for a component of a child of an entity? #18045
-
Sorry for a cumbersome title. I have a
What would be the best way to expose a getter/setter for |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I suppose there are multiple solution. Here is a solution I often use (something like) : #[derive(Component)]
pub struct TextInput {
pub content: String,
}
#[derive(Component)]
struct TextInputTag;
fn create_text_input(
trigger: Trigger<OnAdd, TextInput>,
mut commands: Commands, inputs: Query<&TextInput>
) {
let input = inputs.get(trigger.entity()).unwrap();
commands.entity(trigger.entity()).with_children(|parent| {
parent.spawn(...);
parent.spawn((Text(input.content.clone()), TextInputTag));
parent.spawn(...);
});
}
fn update_text(
inputs: Query<&TextInput, Changed<TextInput>>,
mut texts: Query<(&mut Text, &Parent), With<TextInputTag>>
) {
for (mut text, parent) in &mut texts {
if let Ok(input) = inputs.get(**parent) {
text.0 = input.content.clone();
}
}
}
pub struct InputTextPlugin;
impl Plugin for InputTextPlugin {
fn build(app: &mut App) {
app.add_system(Update, update_text).observe(create_text_input);
}
} |
Beta Was this translation helpful? Give feedback.
-
If I understand your question correctly, you're more interested in a way to hide your custom Entity hierarchy between your two text entities ? You could have a look at the upcoming entity relationships coming in the soon to be released version 0.16.0 (#17398). Or you could just DIY store a component on your #[derive(Component)]
struct TextRef(pub Entity); This way your hierarchy does not matter and can freely change without breaking any user-side code. You just query the |
Beta Was this translation helpful? Give feedback.
If I understand your question correctly, you're more interested in a way to hide your custom Entity hierarchy between your two text entities ?
You could have a look at the upcoming entity relationships coming in the soon to be released version 0.16.0 (#17398).
Or you could just DIY store a component on your
TextInput
entity storing a reference to theText
display entity, something like:This way your hierarchy does not matter and can freely change without breaking any user-side code. You just query the
TextRef
component and access theText
component of the referenced entity.