From ad1691e44a7fa7f3cd610545f5d74f62e3af9497 Mon Sep 17 00:00:00 2001 From: JaySpruce Date: Fri, 28 Feb 2025 18:08:03 -0600 Subject: [PATCH] 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. --- .../bevy_ecs/src/system/commands/entity_command.rs | 13 +++++++++++++ crates/bevy_ecs/src/system/commands/mod.rs | 10 ++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/bevy_ecs/src/system/commands/entity_command.rs b/crates/bevy_ecs/src/system/commands/entity_command.rs index ab0c47bf4e..c73c76dc3a 100644 --- a/crates/bevy_ecs/src/system/commands/entity_command.rs +++ b/crates/bevy_ecs/src/system/commands/entity_command.rs @@ -268,6 +268,19 @@ pub fn observe( } } +/// 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( diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 28fd253bd1..442c4185dc 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -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.