Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trigger::entity() only returns valid entities #14558

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions crates/bevy_ecs/src/observer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,30 @@ impl<'w, E, B: Bundle> Trigger<'w, E, B> {
Ptr::from(&self.event)
}

/// Returns the entity that triggered the observer, could be [`Entity::PLACEHOLDER`].
/// Returns the entity that triggered the observer.
///
/// # Panics
///
/// Panics if the entity is [`Entity::PLACEHOLDER`].
/// Use [`Trigger::get_entity`] if you want to handle the case where the entity is a placeholder.
pub fn entity(&self) -> Entity {
if self.trigger.entity == Entity::PLACEHOLDER {
panic!(
"called `Trigger::entity()` when the target entity was a `Entity::PLACEHOLDER`."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This message does not help a user, as they will mostly not interact with Entity::PLACEHOLDER and probably got this panic while trying to get the entity of a globally triggered observer. Add a hint to this like "Did you try [...]? There is no associated entity in that case."

This comment is also valid for the # Panics documentation, which should mention under which circumstances an underlying Entity would be a placeholder.

);
}
self.trigger.entity
}

/// Returns the entity that triggered the observer, if it's not a placeholder entity.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Returns the entity that triggered the observer, if it's not a placeholder entity.
/// Returns the entity that triggered the observer, if it's not [`Entity::PLACEHOLDER`].

pub fn get_entity(&self) -> Option<Entity> {
if self.trigger.entity == Entity::PLACEHOLDER {
None
} else {
Some(self.trigger.entity)
}
}

/// Enables or disables event propagation, allowing the same event to trigger observers on a chain of different entities.
///
/// The path an event will propagate along is specified by its associated [`Traversal`] component. By default, events
Expand Down Expand Up @@ -665,7 +684,7 @@ mod tests {
.spawn_empty()
.observe(|_: Trigger<EventA>| panic!("Trigger routed to non-targeted entity."));
world.observe(move |obs: Trigger<EventA>, mut res: ResMut<R>| {
assert_eq!(obs.entity(), Entity::PLACEHOLDER);
assert_eq!(obs.get_entity(), None);
res.0 += 1;
});

Expand Down Expand Up @@ -959,7 +978,11 @@ mod tests {

world.observe(
|trigger: Trigger<EventPropagating>, query: Query<&A>, mut res: ResMut<R>| {
if query.get(trigger.entity()).is_ok() {
if trigger
.get_entity()
.map(|entity| query.get(entity).is_ok())
.unwrap_or_default()
Comment on lines +982 to +984
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.get_entity()
.map(|entity| query.get(entity).is_ok())
.unwrap_or_default()
.get_entity()
.is_some_and(|entity| query.get(entity).is_ok())

{
res.0 += 1;
}
},
Expand Down
12 changes: 6 additions & 6 deletions crates/bevy_scene/src/scene_spawner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ mod tests {
})
}

fn observe_trigger(app: &mut App, scene_id: InstanceId, scene_entity: Entity) {
fn observe_trigger(app: &mut App, scene_id: InstanceId, scene_entity: Option<Entity>) {
// Add observer
app.world_mut().observe(
move |trigger: Trigger<SceneInstanceReady>,
Expand All @@ -588,7 +588,7 @@ mod tests {
"`SceneInstanceReady` contains the wrong `InstanceId`"
);
assert_eq!(
trigger.entity(),
trigger.get_entity(),
scene_entity,
"`SceneInstanceReady` triggered on the wrong parent entity"
);
Expand Down Expand Up @@ -626,7 +626,7 @@ mod tests {
});

// Check trigger.
observe_trigger(&mut app, scene_id, Entity::PLACEHOLDER);
observe_trigger(&mut app, scene_id, None);
}

#[test]
Expand All @@ -644,7 +644,7 @@ mod tests {
});

// Check trigger.
observe_trigger(&mut app, scene_id, Entity::PLACEHOLDER);
observe_trigger(&mut app, scene_id, None);
}

#[test]
Expand All @@ -664,7 +664,7 @@ mod tests {
);

// Check trigger.
observe_trigger(&mut app, scene_id, scene_entity);
observe_trigger(&mut app, scene_id, Some(scene_entity));
}

#[test]
Expand All @@ -684,7 +684,7 @@ mod tests {
);

// Check trigger.
observe_trigger(&mut app, scene_id, scene_entity);
observe_trigger(&mut app, scene_id, Some(scene_entity));
}

#[test]
Expand Down
6 changes: 4 additions & 2 deletions examples/ecs/observer_propagation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ fn attack_armor(entities: Query<Entity, With<Armor>>, mut commands: Commands) {
}

fn attack_hits(trigger: Trigger<Attack>, name: Query<&Name>) {
if let Ok(name) = name.get(trigger.entity()) {
info!("Attack hit {}", name);
if let Some(entity) = trigger.get_entity() {
if let Ok(name) = name.get(entity) {
info!("Attack hit {}", name);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
info!("Attack hit {}", name);
info!("Attack hit {name}");

}
}
}

Expand Down
4 changes: 3 additions & 1 deletion examples/ecs/observers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ fn on_remove_mine(

fn explode_mine(trigger: Trigger<Explode>, query: Query<&Mine>, mut commands: Commands) {
// If a triggered event is targeting a specific entity you can access it with `.entity()`
let id = trigger.entity();
let Some(id) = trigger.get_entity() else {
return;
};
let Some(mut entity) = commands.get_entity(id) else {
return;
};
Expand Down