bevy_ecs::system

Trait EntityCommand

Source
pub trait EntityCommand<Marker = ()>: Send + 'static {
    // Required method
    fn apply(self, entity: Entity, world: &mut World);

    // Provided method
    fn with_entity(self, entity: Entity) -> impl Command
       where Self: Sized { ... }
}
Expand description

A Command which gets executed for a given Entity.

§Examples

use bevy_ecs::system::EntityCommand;

#[derive(Resource, Default)]
struct Counter(i64);

/// A `Command` which names an entity based on a global counter.
fn count_name(entity: Entity, world: &mut World) {
    // Get the current value of the counter, and increment it for next time.
    let mut counter = world.resource_mut::<Counter>();
    let i = counter.0;
    counter.0 += 1;

    // Name the entity after the value of the counter.
    world.entity_mut(entity).insert(Name::new(format!("Entity #{i}")));
}

// App creation boilerplate omitted...

fn setup(mut commands: Commands) {
    commands.spawn_empty().queue(count_name);
    commands.spawn_empty().queue(count_name);
}

fn assert_names(named: Query<&Name>) {
    // We use a HashSet because we do not care about the order.
    let names: HashSet<_> = named.iter().map(Name::as_str).collect();
    assert_eq!(names, HashSet::from_iter(["Entity #0", "Entity #1"]));
}

Required Methods§

Source

fn apply(self, entity: Entity, world: &mut World)

Executes this command for the given Entity.

Provided Methods§

Source

fn with_entity(self, entity: Entity) -> impl Command
where Self: Sized,

Returns a Command which executes this EntityCommand for the given Entity.

This method is called when adding an EntityCommand to a command queue via Commands. You can override the provided implementation if you can return a Command with a smaller memory footprint than (Entity, Self). In most cases the provided implementation is sufficient.

Implementors§

Source§

impl<F> EntityCommand for F
where F: FnOnce(Entity, &mut World) + Send + 'static,

Source§

impl<F> EntityCommand<World> for F
where F: FnOnce(EntityWorldMut<'_>) + Send + 'static,