Skip to content

Fix observers' access to relationship data during despawn_related #20258

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
46 changes: 43 additions & 3 deletions crates/bevy_ecs/src/relationship/related_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,12 +299,15 @@ impl<'w> EntityWorldMut<'w> {
/// Despawns entities that relate to this one via the given [`RelationshipTarget`].
/// This entity will not be despawned.
pub fn despawn_related<S: RelationshipTarget>(&mut self) -> &mut Self {
if let Some(sources) = self.take::<S>() {
if let Some(sources) = self.get::<S>() {
// We have to collect here to defer removal, allowing observers and hooks to see this data
// before it is finally removed.
let sources = sources.iter().collect::<Vec<_>>();
self.world_scope(|world| {
for entity in sources.iter() {
for entity in sources {
if let Ok(entity_mut) = world.get_entity_mut(entity) {
entity_mut.despawn();
}
};
}
});
}
Expand Down Expand Up @@ -882,4 +885,41 @@ mod tests {
let data = parent.get::<Parent>().unwrap().data;
assert_eq!(data, 42);
}

#[test]
fn despawn_related_observers_can_access_relationship_data() {
use crate::lifecycle::Replace;
use crate::observer::On;
use crate::prelude::Has;
use crate::system::Query;

#[derive(Component)]
struct MyComponent;

#[derive(Component, Default)]
struct ObserverResult {
success: bool,
}

let mut world = World::new();
let result_entity = world.spawn(ObserverResult::default()).id();

world.add_observer(
move |trigger: On<Replace, MyComponent>,
has_relationship: Query<Has<ChildOf>>,
mut results: Query<&mut ObserverResult>| {
let entity = trigger.target();
if has_relationship.get(entity).unwrap_or(false) {
results.get_mut(result_entity).unwrap().success = true;
}
},
);

let parent = world.spawn_empty().id();
let _child = world.spawn((MyComponent, ChildOf(parent))).id();

world.entity_mut(parent).despawn_related::<Children>();

assert!(world.get::<ObserverResult>(result_entity).unwrap().success);
}
}
Loading