Skip to content

Commit

Permalink
Update EntityCommands::trigger to check for the entity's existence (#…
Browse files Browse the repository at this point in the history
…18071)

## Objective

`EntityCommands::trigger` internally uses `Commands::trigger_targets`,
which means it gets queued using `Commands::queue` rather
`EntityCommands::queue`. This previously wouldn't have made much
difference, but now entity commands check whether the entity exists, and
that check never happens in this case.

## Solution

- Add `entity_command::trigger`, which calls the same function as before
(`World::trigger_targets_with_caller`) but through the `EntityWorldMut`
passed to entity commands.
- Change `EntityCommands::trigger` to queue the new entity command
normally.
  • Loading branch information
JaySpruce authored Mar 1, 2025
1 parent 780f658 commit ad1691e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
13 changes: 13 additions & 0 deletions crates/bevy_ecs/src/system/commands/entity_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,19 @@ pub fn observe<E: Event, B: Bundle, M>(
}
}

/// An [`EntityCommand`] that sends a [`Trigger`](crate::observer::Trigger) targeting an entity.
/// This will run any [`Observer`](crate::observer::Observer) of the given [`Event`] watching the entity.
#[track_caller]
pub fn trigger(event: impl Event) -> impl EntityCommand {
let caller = MaybeLocation::caller();
move |mut entity: EntityWorldMut| {
let id = entity.id();
entity.world_scope(|world| {
world.trigger_targets_with_caller(event, id, caller);
});
}
}

/// An [`EntityCommand`] that clones parts of an entity onto another entity,
/// configured through [`EntityClonerBuilder`].
pub fn clone_with(
Expand Down
10 changes: 4 additions & 6 deletions crates/bevy_ecs/src/system/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1916,13 +1916,11 @@ impl<'a> EntityCommands<'a> {
&mut self.commands
}

/// Sends a [`Trigger`] targeting this entity. This will run any [`Observer`] of the `event` that
/// watches this entity.
///
/// [`Trigger`]: crate::observer::Trigger
/// Sends a [`Trigger`](crate::observer::Trigger) targeting the entity.
/// This will run any [`Observer`] of the given [`Event`] watching this entity.
#[track_caller]
pub fn trigger(&mut self, event: impl Event) -> &mut Self {
self.commands.trigger_targets(event, self.entity);
self
self.queue(entity_command::trigger(event))
}

/// Creates an [`Observer`] listening for events of type `E` targeting this entity.
Expand Down

0 comments on commit ad1691e

Please sign in to comment.