use bevy::prelude::*;
pub fn attach_or_despawn(commands: &mut Commands, parent: Entity, child: Entity) {
commands.queue(move |world: &mut World| {
if world.get_entity(parent).is_ok() {
if let Ok(mut ec) = world.get_entity_mut(parent) {
ec.add_child(child);
}
} else if let Ok(ec) = world.get_entity_mut(child) {
ec.despawn();
}
});
}
pub fn attach_children_or_despawn(commands: &mut Commands, parent: Entity, children: &[Entity]) {
let children: Box<[Entity]> = children.into();
commands.queue(move |world: &mut World| {
if world.get_entity(parent).is_ok() {
if let Ok(mut ec) = world.get_entity_mut(parent) {
ec.add_children(&children);
}
} else {
for child in &children {
if let Ok(ec) = world.get_entity_mut(*child) {
ec.despawn();
}
}
}
});
}
pub fn insert_if_alive<B: Bundle>(commands: &mut Commands, entity: Entity, bundle: B) {
commands.queue(move |world: &mut World| {
if let Ok(mut ec) = world.get_entity_mut(entity) {
ec.insert(bundle);
}
});
}
pub fn is_descendant_of(entity: Entity, ancestor: Entity, parents: &Query<&ChildOf>) -> bool {
let mut current = entity;
for _ in 0..50 {
if current == ancestor {
return true;
}
if let Ok(child_of) = parents.get(current) {
current = child_of.parent();
} else {
return false;
}
}
false
}
pub fn find_ancestor<'a, C: Component>(
entity: Entity,
query: &'a Query<&C>,
parents: &Query<&ChildOf>,
) -> Option<(Entity, &'a C)> {
let mut current = entity;
for _ in 0..50 {
if let Ok(component) = query.get(current) {
return Some((current, component));
}
if let Ok(child_of) = parents.get(current) {
current = child_of.parent();
} else {
return None;
}
}
None
}