Update EntityCommands::trigger to check for the entity's existence (#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.
This commit is contained in:
JaySpruce 2025-02-28 18:08:03 -06:00 committed by GitHub
parent 780f658f2c
commit ad1691e44a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 6 deletions

View File

@ -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, /// An [`EntityCommand`] that clones parts of an entity onto another entity,
/// configured through [`EntityClonerBuilder`]. /// configured through [`EntityClonerBuilder`].
pub fn clone_with( pub fn clone_with(

View File

@ -1916,13 +1916,11 @@ impl<'a> EntityCommands<'a> {
&mut self.commands &mut self.commands
} }
/// Sends a [`Trigger`] targeting this entity. This will run any [`Observer`] of the `event` that /// Sends a [`Trigger`](crate::observer::Trigger) targeting the entity.
/// watches this entity. /// This will run any [`Observer`] of the given [`Event`] watching this entity.
/// #[track_caller]
/// [`Trigger`]: crate::observer::Trigger
pub fn trigger(&mut self, event: impl Event) -> &mut Self { pub fn trigger(&mut self, event: impl Event) -> &mut Self {
self.commands.trigger_targets(event, self.entity); self.queue(entity_command::trigger(event))
self
} }
/// Creates an [`Observer`] listening for events of type `E` targeting this entity. /// Creates an [`Observer`] listening for events of type `E` targeting this entity.