bevy icon indicating copy to clipboard operation
bevy copied to clipboard

Add `EntityWorldMut::commands` method

Open benfrankel opened this issue 1 year ago • 3 comments

What problem does this solve or what need does it fill?

I'm implementing UI widgets as EntityCommands to get an API like this:

commands.spawn_empty().add(my_ui_widget).insert(Name::new("CustomName"))

I want my parent widget to create child widgets with entity.add(my_child_widget), but entity is an EntityWorldMut, not an EntityCommands, so it has no .add method.

What solution would you like?

fn my_parent_widget(mut entity: EntityWorldMut) {
    entity.commands().add(my_child_widget).insert(...);
}

This is a natural solution, because EntityWorldMut::commands -> EntityCommands would parallel World::commands -> Commands.

What alternative(s) have you considered?

  1. EntityWorldMut::add:
fn my_parent_widget(mut entity: EntityWorldMut) {
    entity.add(my_child_widget).insert(...);
}
  1. Just work around it:
fn my_parent_widget(mut entity: EntityWorldMut) {
    {
        let id = entity.id();
        entity.world_scope(|world| world.commands().add(my_child_widget.with_entity(id)));
    }
    entity.insert(...);
}

benfrankel avatar Jul 11 '24 09:07 benfrankel

An EntityWorldMut::add(entity_command) method would be even better for my use case, but I'm not proposing that right now because I'm not sure it would fit the overall API. There's currently no World::add(command) method.

EntityWorldMut::command fills a gap, on the other hand.

benfrankel avatar Jul 11 '24 09:07 benfrankel

Related to #14231.

alice-i-cecile avatar Jul 11 '24 13:07 alice-i-cecile

BTW here's a copy-pastable workaround as an extension trait :smile:

pub trait EntityWorldMutExtAdd {
    fn add<M: 'static>(&mut self, command: impl EntityCommand<M>) -> &mut Self;
}

impl EntityWorldMutExtAdd for EntityWorldMut<'_> {
    fn add<M: 'static>(&mut self, command: impl EntityCommand<M>) -> &mut Self {
        let id = self.id();
        self.world_scope(|world| world.commands().add(command.with_entity(id)));
        self
    }
}

I can't seem to implement fn commands because EntityWorldMut's fields are pub(crate) and lifetimes get in the way.

benfrankel avatar Jul 11 '24 17:07 benfrankel