Skip to content

Commit

Permalink
fix panic when moving child (#8346)
Browse files Browse the repository at this point in the history
# Objective
When changing an Entity's `Parent` to a new one from an old `Parent`
that doesn't exist, Bevy panics. Fixes #8337.

## Solution

Use `get_entity_mut` instead of `entity_mut` in `remove_from_children`.

---------

Co-authored-by: James Liu <[email protected]>
  • Loading branch information
B-Reif and james7132 authored Apr 17, 2023
1 parent 8ed7723 commit 7604464
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions crates/bevy_hierarchy/src/child_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,15 @@ fn update_parent(world: &mut World, child: Entity, new_parent: Entity) -> Option
///
/// Removes the [`Children`] component from the parent if it's empty.
fn remove_from_children(world: &mut World, parent: Entity, child: Entity) {
let mut parent = world.entity_mut(parent);
if let Some(mut children) = parent.get_mut::<Children>() {
children.0.retain(|x| *x != child);
if children.is_empty() {
parent.remove::<Children>();
}
let Some(mut parent) = world.get_entity_mut(parent) else {
return;
};
let Some(mut children) = parent.get_mut::<Children>() else {
return;
};
children.0.retain(|x| *x != child);
if children.is_empty() {
parent.remove::<Children>();
}
}

Expand Down Expand Up @@ -653,6 +656,23 @@ mod tests {
);
}

// regression test for https://github.com/bevyengine/bevy/pull/8346
#[test]
fn set_parent_of_orphan() {
let world = &mut World::new();

let [a, b, c] = std::array::from_fn(|_| world.spawn_empty().id());
world.entity_mut(a).set_parent(b);
assert_parent(world, a, Some(b));
assert_children(world, b, Some(&[a]));

world.entity_mut(b).despawn();
world.entity_mut(a).set_parent(c);

assert_parent(world, a, Some(c));
assert_children(world, c, Some(&[a]));
}

#[test]
fn remove_parent() {
let world = &mut World::new();
Expand Down

0 comments on commit 7604464

Please sign in to comment.