Add entity .trigger() methods (#14752)

# Objective

Fix https://github.com/bevyengine/bevy/issues/14233.

## Solution

Add `EntityCommands::trigger` and `EntityWorldMut::trigger`.

## Testing

- Not tested.
This commit is contained in:
Ben Frankel 2024-08-15 17:16:06 +03:00 committed by GitHub
parent a44278aee6
commit d849941dac
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 1 deletions

View file

@ -777,7 +777,7 @@ impl<'w, 's> Commands<'w, 's> {
self.add(TriggerEvent { event, targets }); self.add(TriggerEvent { event, targets });
} }
/// Spawn an [`Observer`] and returns the [`EntityCommands`] associated with the entity that stores the observer. /// Spawns an [`Observer`] and returns the [`EntityCommands`] associated with the entity that stores the observer.
pub fn observe<E: Event, B: Bundle, M>( pub fn observe<E: Event, B: Bundle, M>(
&mut self, &mut self,
observer: impl IntoObserverSystem<E, B, M>, observer: impl IntoObserverSystem<E, B, M>,
@ -1210,6 +1210,15 @@ impl EntityCommands<'_> {
self.commands.reborrow() self.commands.reborrow()
} }
/// Sends a [`Trigger`] targeting this entity. This will run any [`Observer`] of the `event` that
/// watches this entity.
///
/// [`Trigger`]: crate::observer::Trigger
pub fn trigger(&mut self, event: impl Event) -> &mut Self {
self.commands.trigger_targets(event, self.entity);
self
}
/// Creates an [`Observer`] listening for a trigger of type `T` that targets this entity. /// Creates an [`Observer`] listening for a trigger of type `T` that targets this entity.
pub fn observe<E: Event, B: Bundle, M>( pub fn observe<E: Event, B: Bundle, M>(
&mut self, &mut self,

View file

@ -1443,6 +1443,12 @@ impl<'w> EntityWorldMut<'w> {
} }
} }
/// Triggers the given `event` for this entity, which will run any observers watching for it.
pub fn trigger(&mut self, event: impl Event) -> &mut Self {
self.world.trigger_targets(event, self.entity);
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.
/// In order to trigger the callback the entity must also match the query when the event is fired. /// In order to trigger the callback the entity must also match the query when the event is fired.
pub fn observe<E: Event, B: Bundle, M>( pub fn observe<E: Event, B: Bundle, M>(