InstanceCommands

Struct InstanceCommands 

Source
pub struct InstanceCommands<'a, T>(/* private fields */)
where
    T: Kind;
Expand description

EntityCommands with kind semantics.

§Usage

On its own, this type is not very useful. Instead, it is designed to be extended using traits. This allows you to design commands for a specific kind of an entity in a type-safe manner.

§Example


#[derive(Component)]
struct Apple;

#[derive(Component)]
struct Eat;

trait EatApple {
    fn eat(&mut self);
}

impl EatApple for InstanceCommands<'_, Apple> {
    fn eat(&mut self) {
        info!("Crunch!");
        self.despawn();
    }
}

fn eat_apples(apples: Query<Instance<Apple>, With<Eat>>, mut commands: Commands) {
    for apple in apples.iter() {
        commands.instance(apple).eat();
    }
}

Implementations§

Source§

impl<'a, T> InstanceCommands<'a, T>
where T: Kind,

Source

pub unsafe fn from_entity_unchecked( entity: EntityCommands<'a>, ) -> InstanceCommands<'a, T>

Creates a new InstanceCommands<T> from EntityCommands without any validation.

§Safety

Assumes entity is a valid instance of kind T.

Source

pub fn from_entity( entity: EntityRef<'_>, commands: &'a mut Commands<'_, '_>, ) -> Option<InstanceCommands<'a, T>>
where T: Component,

Creates a new InstanceCommands<T> from EntityRef if it contains a Component of type T.

Source

pub fn instance(&self) -> Instance<T>

Returns the associated Instance<T>.

Source

pub fn as_entity(&mut self) -> &mut EntityCommands<'a>

Returns the associated EntityCommands.

Source

pub fn insert(&mut self, bundle: impl Bundle) -> &mut InstanceCommands<'a, T>

Equivalent to EntityCommands::insert, but it returns self to maintain kind semantics.

Source

pub fn remove<U>(&mut self) -> &mut InstanceCommands<'a, T>
where U: Component,

Equivalent to EntityCommands::insert, but it returns self to maintain kind semantics.

Source

pub fn try_remove<U>(&mut self) -> &mut InstanceCommands<'a, T>
where U: Component,

Equivalent to EntityCommands::try_insert, but it returns self to maintain kind semantics.

Source

pub fn reborrow(&mut self) -> InstanceCommands<'_, T>

Returns an InstanceCommands with a smaller lifetime.

This is useful if you have &mut InstanceCommands but you need InstanceCommands.

Source

pub fn cast_into<U>(self) -> InstanceCommands<'a, U>
where U: Kind, T: CastInto<U>,

Converts this InstanceCommands<T> into an InstanceCommands<U>, given that T implements CastInto<U>.

Methods from Deref<Target = EntityCommands<'a>>§

Source

pub fn with_children( &mut self, func: impl FnOnce(&mut RelatedSpawnerCommands<'_, ChildOf>), ) -> &mut EntityCommands<'a>

Spawns children of this entity (with a ChildOf relationship) by taking a function that operates on a ChildSpawner.

Source

pub fn add_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'a>

Adds the given children to this entity.

Source

pub fn clear_children(&mut self) -> &mut EntityCommands<'a>

👎Deprecated: Use detach_all_children() instead

Removes all the children from this entity. See also detach_all_related

Source

pub fn detach_all_children(&mut self) -> &mut EntityCommands<'a>

Removes all the parent-child relationships from this entity. To despawn the child entities, instead use EntityWorldMut::despawn_children. See also detach_all_related

Source

pub fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityCommands<'a>

Insert children at specific index. See also insert_related.

Source

pub fn insert_child( &mut self, index: usize, child: Entity, ) -> &mut EntityCommands<'a>

Insert children at specific index. See also insert_related.

Source

pub fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'a>

Adds the given child to this entity.

Source

pub fn remove_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>

👎Deprecated: Use detach_children() instead

Removes the relationship between this entity and the given entities.

Source

pub fn detach_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>

Removes the parent-child relationship between this entity and the given entities. Does not despawn the children.

Source

pub fn remove_child(&mut self, child: Entity) -> &mut EntityCommands<'a>

👎Deprecated: Use detach_child() instead

Removes the relationship between this entity and the given entity.

Source

pub fn detach_child(&mut self, child: Entity) -> &mut EntityCommands<'a>

Removes the parent-child relationship between this entity and the given entity. Does not despawn the child.

Source

pub fn replace_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>

Replaces the children on this entity with a new list of children.

Source

pub fn replace_children_with_difference( &mut self, entities_to_unrelate: &[Entity], entities_to_relate: &[Entity], newly_related_entities: &[Entity], ) -> &mut EntityCommands<'a>

Replaces all the related entities with a new set of entities.

§Warning

Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes. Refer to EntityWorldMut::replace_related_with_difference for a list of these invariants.

§Panics

Panics when debug assertions are enabled if an invariant is broken and the command is executed.

Source

pub fn with_child(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>

Spawns the passed bundle and adds it to this entity as a child.

For efficient spawning of multiple children, use with_children.

Spawns a entity related to this entity (with the R relationship) by taking a bundle

Spawns entities related to this entity (with the R relationship) by taking a function that operates on a RelatedSpawner.

Relates the given entities to this entity with the relation R.

See add_one_related if you want relate only one entity.

Removes the relation R between this entity and all its related entities.

Relates the given entities to this entity with the relation R, starting at this particular index.

If the related has duplicates, a related entity will take the index of its last occurrence in related. If the indices go out of bounds, they will be clamped into bounds. This will not re-order existing related entities unless they are in related.

Relates the given entity to this with the relation R.

See add_related if you want to relate more than one entity.

Removes the relation R between this entity and the given entities.

Replaces all the related entities with the given set of new related entities.

Replaces all the related entities with a new set of entities.

§Warning

Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes. Refer to EntityWorldMut::replace_related_with_difference for a list of these invariants.

§Panics

Panics when debug assertions are enable, an invariant is are broken and the command is executed.

Despawns entities that relate to this one via the given RelationshipTarget. This entity will not be despawned.

Source

pub fn despawn_children(&mut self) -> &mut EntityCommands<'a>

Despawns the children of this entity. This entity will not be despawned.

This is a specialization of despawn_related, a more general method for despawning via relationships.

Source

pub fn insert_recursive<S>( &mut self, bundle: impl Bundle + Clone, ) -> &mut EntityCommands<'a>

Inserts a component or bundle of components into the entity and all related entities, traversing the relationship tracked in S in a breadth-first manner.

§Warning

This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.

Source

pub fn remove_recursive<S, B>(&mut self) -> &mut EntityCommands<'a>

Removes a component or bundle of components of type B from the entity and all related entities, traversing the relationship tracked in S in a breadth-first manner.

§Warning

This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.

Source

pub fn id(&self) -> Entity

Returns the Entity id of the entity.

§Example
fn my_system(mut commands: Commands) {
    let entity_id = commands.spawn_empty().id();
}
Source

pub fn reborrow(&mut self) -> EntityCommands<'_>

Returns an EntityCommands with a smaller lifetime.

This is useful if you have &mut EntityCommands but you need EntityCommands.

Source

pub fn entry<T>(&mut self) -> EntityEntryCommands<'_, T>
where T: Component,

Get an EntityEntryCommands for the Component T, allowing you to modify it or insert it if it isn’t already present.

See also insert_if_new, which lets you insert a Bundle without overwriting it.

§Example
#[derive(Component)]
struct Level(u32);


#[derive(Component, Default)]
struct Mana {
    max: u32,
    current: u32,
}

fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
    // If a component already exists then modify it, otherwise insert a default value
    commands
        .entity(player.entity)
        .entry::<Level>()
        .and_modify(|mut lvl| lvl.0 += 1)
        .or_insert(Level(0));

    // Add a default value if none exists, and then modify the existing or new value
    commands
        .entity(player.entity)
        .entry::<Mana>()
        .or_default()
        .and_modify(|mut mana| {
            mana.max += 10;
            mana.current = mana.max;
    });
}
Source

pub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>

Adds a Bundle of components to the entity.

This will overwrite any previous value(s) of the same component type. See EntityCommands::insert_if_new to keep the old value instead.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        // You can insert individual components:
        .insert(Defense(10))
        // You can also insert pre-defined bundles of components:
        .insert(CombatBundle {
            health: Health(100),
            strength: Strength(40),
        })
        // You can also insert tuples of components and bundles.
        // This is equivalent to the calls above:
        .insert((
            Defense(10),
            CombatBundle {
                health: Health(100),
                strength: Strength(40),
            },
        ));
}
Source

pub fn insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
where F: FnOnce() -> bool,

Adds a Bundle of components to the entity if the predicate returns true.

This is useful for chaining method calls.

§Example
#[derive(Component)]
struct StillLoadingStats;
#[derive(Component)]
struct Health(u32);

fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        .insert_if(Health(10), || !player.is_spectator())
        .remove::<StillLoadingStats>();
}
Source

pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>

Adds a Bundle of components to the entity without overwriting.

This is the same as EntityCommands::insert, but in case of duplicate components will leave the old values instead of replacing them with new ones.

See also entry, which lets you modify a Component if it’s present, as well as initialize it with a default value.

Source

pub fn insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
where F: FnOnce() -> bool,

Adds a Bundle of components to the entity without overwriting if the predicate returns true.

This is the same as EntityCommands::insert_if, but in case of duplicate components will leave the old values instead of replacing them with new ones.

Source

pub unsafe fn insert_by_id<T>( &mut self, component_id: ComponentId, value: T, ) -> &mut EntityCommands<'a>
where T: Send + 'static,

Adds a dynamic Component to the entity.

This will overwrite any previous value(s) of the same component type.

You should prefer to use the typed API EntityCommands::insert where possible.

§Safety
  • ComponentId must be from the same world as self.
  • T must have the same layout as the one passed during component_id creation.
Source

pub unsafe fn try_insert_by_id<T>( &mut self, component_id: ComponentId, value: T, ) -> &mut EntityCommands<'a>
where T: Send + 'static,

Adds a dynamic Component to the entity.

This will overwrite any previous value(s) of the same component type.

You should prefer to use the typed API EntityCommands::try_insert where possible.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

§Safety
  • ComponentId must be from the same world as self.
  • T must have the same layout as the one passed during component_id creation.
Source

pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>

Adds a Bundle of components to the entity.

This will overwrite any previous value(s) of the same component type.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands.entity(player.entity)
        // You can insert individual components:
        .try_insert(Defense(10))
        // You can also insert tuples of components:
        .try_insert(CombatBundle {
            health: Health(100),
            strength: Strength(40),
        });

    // Suppose this occurs in a parallel adjacent system or process.
    commands.entity(player.entity).despawn();

    // This will not panic nor will it add the component.
    commands.entity(player.entity).try_insert(Defense(5));
}
Source

pub fn try_insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
where F: FnOnce() -> bool,

Adds a Bundle of components to the entity if the predicate returns true.

This is useful for chaining method calls.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

Source

pub fn try_insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
where F: FnOnce() -> bool,

Adds a Bundle of components to the entity without overwriting if the predicate returns true.

This is the same as EntityCommands::try_insert_if, but in case of duplicate components will leave the old values instead of replacing them with new ones.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

Source

pub fn try_insert_if_new( &mut self, bundle: impl Bundle, ) -> &mut EntityCommands<'a>

Adds a Bundle of components to the entity without overwriting.

This is the same as EntityCommands::try_insert, but in case of duplicate components will leave the old values instead of replacing them with new ones.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

Source

pub fn remove<B>(&mut self) -> &mut EntityCommands<'a>
where B: Bundle,

Removes a Bundle of components from the entity.

This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.

This will emit a warning if the entity does not exist.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        // You can remove individual components:
        .remove::<Defense>()
        // You can also remove pre-defined bundles of components:
        .remove::<CombatBundle>()
        // You can also remove tuples of components and bundles.
        // This is equivalent to the calls above:
        .remove::<(Defense, CombatBundle)>();
}
Source

pub fn remove_if<B>( &mut self, condition: impl FnOnce() -> bool, ) -> &mut EntityCommands<'a>
where B: Bundle,

Removes a Bundle of components from the entity if the predicate returns true.

This is useful for chaining method calls.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        .remove_if::<(Defense, CombatBundle)>(|| !player.is_spectator());
}
Source

pub fn try_remove_if<B>( &mut self, condition: impl FnOnce() -> bool, ) -> &mut EntityCommands<'a>
where B: Bundle,

Removes a Bundle of components from the entity if the predicate returns true.

This is useful for chaining method calls.

§Note

If the entity does not exist when this command is executed, the resulting error will be ignored.

Source

pub fn try_remove<B>(&mut self) -> &mut EntityCommands<'a>
where B: Bundle,

Removes a Bundle of components from the entity.

This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.

Unlike Self::remove, this will not emit a warning if the entity does not exist.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        // You can remove individual components:
        .try_remove::<Defense>()
        // You can also remove pre-defined bundles of components:
        .try_remove::<CombatBundle>()
        // You can also remove tuples of components and bundles.
        // This is equivalent to the calls above:
        .try_remove::<(Defense, CombatBundle)>();
}
Source

pub fn remove_with_requires<B>(&mut self) -> &mut EntityCommands<'a>
where B: Bundle,

Removes a Bundle of components from the entity, and also removes any components required by the components in the bundle.

This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.

§Example
#[derive(Component)]
#[require(B)]
struct A;
#[derive(Component, Default)]
struct B;

fn remove_with_requires_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        // Removes both A and B from the entity, because B is required by A.
        .remove_with_requires::<A>();
}
Source

pub fn remove_by_id( &mut self, component_id: ComponentId, ) -> &mut EntityCommands<'a>

Removes a dynamic Component from the entity if it exists.

§Panics

Panics if the provided ComponentId does not exist in the World.

Source

pub fn clear(&mut self) -> &mut EntityCommands<'a>

Removes all components associated with the entity.

Source

pub fn despawn(&mut self)

Despawns the entity.

This will emit a warning if the entity does not exist.

§Note

This will also despawn the entities in any RelationshipTarget that is configured to despawn descendants.

For example, this will recursively despawn Children.

§Example
fn remove_character_system(
    mut commands: Commands,
    character_to_remove: Res<CharacterToRemove>
) {
    commands.entity(character_to_remove.entity).despawn();
}
Source

pub fn try_despawn(&mut self)

Despawns the entity.

Unlike Self::despawn, this will not emit a warning if the entity does not exist.

§Note

This will also despawn the entities in any RelationshipTarget that is configured to despawn descendants.

For example, this will recursively despawn Children.

Source

pub fn queue<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>

Pushes an EntityCommand to the queue, which will get executed for the current Entity.

The default error handler will be used to handle error cases. Every EntityCommand checks whether the entity exists at the time of execution and returns an error if it does not.

To use a custom error handler, see EntityCommands::queue_handled.

The command can be:

§Example
commands
    .spawn_empty()
    // Closures with this signature implement `EntityCommand`.
    .queue(|entity: EntityWorldMut| {
        println!("Executed an EntityCommand for {}", entity.id());
    });
Source

pub fn queue_handled<C, T, M>( &mut self, command: C, error_handler: fn(BevyError, ErrorContext), ) -> &mut EntityCommands<'a>

Pushes an EntityCommand to the queue, which will get executed for the current Entity.

The given error_handler will be used to handle error cases. Every EntityCommand checks whether the entity exists at the time of execution and returns an error if it does not.

To implicitly use the default error handler, see EntityCommands::queue.

The command can be:

§Example
use bevy_ecs::error::warn;

commands
    .spawn_empty()
    // Closures with this signature implement `EntityCommand`.
    .queue_handled(
        |entity: EntityWorldMut| -> Result {
            let value: usize = "100".parse()?;
            println!("Successfully parsed the value {} for entity {}", value, entity.id());
            Ok(())
        },
        warn
    );
Source

pub fn queue_silenced<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>

Pushes an EntityCommand to the queue, which will get executed for the current Entity.

Unlike EntityCommands::queue_handled, this will completely ignore any errors that occur.

Source

pub fn retain<B>(&mut self) -> &mut EntityCommands<'a>
where B: Bundle,

Removes all components except the given Bundle from the entity.

§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);

#[derive(Bundle)]
struct CombatBundle {
    health: Health,
    strength: Strength,
}

fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
    commands
        .entity(player.entity)
        // You can retain a pre-defined Bundle of components,
        // with this removing only the Defense component.
        .retain::<CombatBundle>()
        // You can also retain only a single component.
        .retain::<Health>();
}
Source

pub fn log_components(&mut self) -> &mut EntityCommands<'a>

Logs the components of the entity at the info level.

Source

pub fn commands(&mut self) -> Commands<'_, '_>

Returns the underlying Commands.

Source

pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a>

Returns a mutable reference to the underlying Commands.

Source

pub fn observe<E, B, M>( &mut self, observer: impl IntoObserverSystem<E, B, M>, ) -> &mut EntityCommands<'a>
where E: EntityEvent, B: Bundle,

Creates an Observer watching for an EntityEvent of type E whose EntityEvent::event_target targets this entity.

Source

pub fn clone_with_opt_out( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> &mut EntityCommands<'a>

Clones parts of an entity (components, observers, etc.) onto another entity, configured through EntityClonerBuilder.

The other entity will receive all the components of the original that implement Clone or Reflect except those that are denied in the config.

§Panics

The command will panic when applied if the target entity does not exist.

§Example

Configure through EntityClonerBuilder<OptOut> as follows:

#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);

fn example_system(mut commands: Commands) {
    // Create an empty entity.
    let target = commands.spawn_empty().id();

    // Create a new entity and keep its EntityCommands.
    let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));

    // Clone ComponentA but not ComponentB onto the target.
    entity.clone_with_opt_out(target, |builder| {
        builder.deny::<ComponentB>();
    });
}

See EntityClonerBuilder for more options.

Source

pub fn clone_with_opt_in( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> &mut EntityCommands<'a>

Clones parts of an entity (components, observers, etc.) onto another entity, configured through EntityClonerBuilder.

The other entity will receive only the components of the original that implement Clone or Reflect and are allowed in the config.

§Panics

The command will panic when applied if the target entity does not exist.

§Example

Configure through EntityClonerBuilder<OptIn> as follows:

#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);

fn example_system(mut commands: Commands) {
    // Create an empty entity.
    let target = commands.spawn_empty().id();

    // Create a new entity and keep its EntityCommands.
    let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));

    // Clone ComponentA but not ComponentB onto the target.
    entity.clone_with_opt_in(target, |builder| {
        builder.allow::<ComponentA>();
    });
}

See EntityClonerBuilder for more options.

Source

pub fn clone_and_spawn(&mut self) -> EntityCommands<'_>

Spawns a clone of this entity and returns the EntityCommands of the clone.

The clone will receive all the components of the original that implement Clone or Reflect.

To configure cloning behavior (such as only cloning certain components), use EntityCommands::clone_and_spawn_with_opt_out/ opt_out.

§Note

If the original entity does not exist when this command is applied, the returned entity will have no components.

§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);

fn example_system(mut commands: Commands) {
    // Create a new entity and store its EntityCommands.
    let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));

    // Create a clone of the entity.
    let mut entity_clone = entity.clone_and_spawn();
}
Source

pub fn clone_and_spawn_with_opt_out( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> EntityCommands<'_>

Spawns a clone of this entity and allows configuring cloning behavior using EntityClonerBuilder, returning the EntityCommands of the clone.

The clone will receive all the components of the original that implement Clone or Reflect except those that are denied in the config.

See the methods on EntityClonerBuilder<OptOut> for more options.

§Note

If the original entity does not exist when this command is applied, the returned entity will have no components.

§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);

fn example_system(mut commands: Commands) {
    // Create a new entity and store its EntityCommands.
    let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));

    // Create a clone of the entity with ComponentA but without ComponentB.
    let mut entity_clone = entity.clone_and_spawn_with_opt_out(|builder| {
        builder.deny::<ComponentB>();
    });
}
Source

pub fn clone_and_spawn_with_opt_in( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> EntityCommands<'_>

Spawns a clone of this entity and allows configuring cloning behavior using EntityClonerBuilder, returning the EntityCommands of the clone.

The clone will receive only the components of the original that implement Clone or Reflect and are allowed in the config.

See the methods on EntityClonerBuilder<OptIn> for more options.

§Note

If the original entity does not exist when this command is applied, the returned entity will have no components.

§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);

fn example_system(mut commands: Commands) {
    // Create a new entity and store its EntityCommands.
    let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));

    // Create a clone of the entity with ComponentA but without ComponentB.
    let mut entity_clone = entity.clone_and_spawn_with_opt_in(|builder| {
        builder.allow::<ComponentA>();
    });
}
Source

pub fn clone_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>
where B: Bundle,

Clones the specified components of this entity and inserts them into another entity.

Components can only be cloned if they implement Clone or Reflect.

§Panics

The command will panic when applied if the target entity does not exist.

Source

pub fn move_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>
where B: Bundle,

Moves the specified components of this entity into another entity.

Components with Ignore clone behavior will not be moved, while components that have a Custom clone behavior will be cloned using it and then removed from the source entity. All other components will be moved without any other special handling.

Note that this will trigger on_remove hooks/observers on this entity and on_insert/on_add hooks/observers on the target entity.

§Panics

The command will panic when applied if the target entity does not exist.

Source

pub fn trigger<'t, E>( &mut self, event_fn: impl FnOnce(Entity) -> E, ) -> &mut EntityCommands<'a>
where E: EntityEvent, <E as Event>::Trigger<'t>: Default,

Passes the current entity into the given function, and triggers the EntityEvent returned by that function.

§Example

A surprising number of functions meet the trait bounds for event_fn:


#[derive(EntityEvent)]
struct Explode(Entity);

impl From<Entity> for Explode {
   fn from(entity: Entity) -> Self {
      Explode(entity)
   }
}


fn trigger_via_constructor(mut commands: Commands) {
    // The fact that `Explode` is a single-field tuple struct
    // ensures that `Explode(entity)` is a function that generates
    // an EntityEvent, meeting the trait bounds for `event_fn`.
    commands.spawn_empty().trigger(Explode);

}


fn trigger_via_from_trait(mut commands: Commands) {
    // This variant also works for events like `struct Explode { entity: Entity }`
    commands.spawn_empty().trigger(Explode::from);
}

fn trigger_via_closure(mut commands: Commands) {
    commands.spawn_empty().trigger(|entity| Explode(entity));
}

Trait Implementations§

Source§

impl<T> ContainsInstance<T> for InstanceCommands<'_, T>
where T: Kind,

Source§

fn instance(&self) -> Instance<T>

Returns the associated Instance<T>.
Source§

fn entity(&self) -> Entity

Returns the Entity of the associated Instance<T>.
Source§

impl<'a, T> Deref for InstanceCommands<'a, T>
where T: Kind,

Source§

type Target = EntityCommands<'a>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<InstanceCommands<'a, T> as Deref>::Target

Dereferences the value.
Source§

impl<T> DerefMut for InstanceCommands<'_, T>
where T: Kind,

Source§

fn deref_mut(&mut self) -> &mut <InstanceCommands<'_, T> as Deref>::Target

Mutably dereferences the value.
Source§

impl<'a, T> From<&InstanceCommands<'a, T>> for Instance<T>
where T: Kind,

Source§

fn from(commands: &InstanceCommands<'a, T>) -> Instance<T>

Converts to this type from the input type.
Source§

impl<'a, T> From<InstanceCommands<'a, T>> for Instance<T>
where T: Kind,

Source§

fn from(commands: InstanceCommands<'a, T>) -> Instance<T>

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a, T> Freeze for InstanceCommands<'a, T>

§

impl<'a, T> RefUnwindSafe for InstanceCommands<'a, T>
where T: RefUnwindSafe,

§

impl<'a, T> Send for InstanceCommands<'a, T>

§

impl<'a, T> Sync for InstanceCommands<'a, T>

§

impl<'a, T> Unpin for InstanceCommands<'a, T>
where T: Unpin,

§

impl<'a, T> !UnwindSafe for InstanceCommands<'a, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Static for T
where T: 'static + Send + Sync,