3

Assume I have something like this:

use bevy::prelude::*;

// Bevy style tag
struct &CharacterBox;

// Somewhere to store the entity
pub struct Action {
    pub character_box: Option<Entity>,
};

fn setup( mut commands: Commands, mut action: ResMut<Action> ) {
    if let Some(entity) = commands
        .spawn(UiCameraComponents::default())
        .spawn(NodeComponents { /* snip */ })
        .with_children(|p| {
            p.spawn(ButtonComponents { /* snip, snap */ });
        })
        .with(CharacterBox)
        .current_entity()
    {
        action.character_box = Some(entity);
    }
}

A NodeComponents with a button or two from startup...

...and later I want to add more buttons from a system I've added:

fn do_actions(
    mut commands: Commands,
    action: ChangedRes<Action>,
    mut query: Query<(&CharacterBox, &Children)>,
) {

    if let Some(entity) = commands
        .spawn(ButtonComponents { /* ... */ })
        .current_entity()
    {
        let mut charbox = query.get_mut::<Children>(action.character_box.unwrap()).unwrap();
        // I know this is naïve, I know I can't just push in the entity,
        // but it illustrates my point...
        charbox.push(entity); // How do I achieve this?
    }

}

How do insert my spawned entity (component?) into my NodeComponents.Children?

How do I spawn a component into an already existing component?

Or how do I access NodeComponents.Children.ChildBuilder? Can I query ChildBuilders?

Edit: removed edits.

ippi
  • 9,857
  • 2
  • 39
  • 50
  • Please [edit] your question to contain a [mre]. – trent Oct 21 '20 at 03:50
  • 1
    @trentcl I disagree about the MRE, The things I snipped out are verbose and irrelevant. The things semi-relevant (like Action) is all implied by how bevy works. I see what you are getting at, but you don't need to see 10 lines of app.addResource and addSystem when I'm not asking to fix my code. I'm asking "how do I do this specfic thing". – ippi Oct 21 '20 at 04:28
  • Fair enough, I edited in the two stucts, because I admit there might be some guesswork required. Initialization is still omitted. – ippi Oct 21 '20 at 04:35

1 Answers1

2

Anyway, here is how I solved it:

 let parent_entity = action.character_box.unwrap();
 let new_entity = commands
      .spawn(ButtonComponents { /* ... */ })
      .current_entity()
      .unwrap();

 commands.push_children(parent_entity, &[c]);

(With nested NodeComponents, I had to spawn them seperately, and then push each entity into the other, because to my knowledge there is no way to get the entity from a ChildBuilder, only by using commands.spawn(...).current_entity(). )

ippi
  • 9,857
  • 2
  • 39
  • 50