bevy_hierarchy/components/parent.rs
1#[cfg(feature = "reflect")]
2use bevy_ecs::reflect::{ReflectComponent, ReflectMapEntities};
3use bevy_ecs::{
4 component::Component,
5 entity::{Entity, EntityMapper, MapEntities},
6 world::{FromWorld, World},
7};
8use std::ops::Deref;
9
10/// Holds a reference to the parent entity of this entity.
11/// This component should only be present on entities that actually have a parent entity.
12///
13/// Parent entity must have this entity stored in its [`Children`] component.
14/// It is hard to set up parent/child relationships manually,
15/// consider using higher level utilities like [`BuildChildren::with_children`].
16///
17/// See [`HierarchyQueryExt`] for hierarchy related methods on [`Query`].
18///
19/// [`HierarchyQueryExt`]: crate::query_extension::HierarchyQueryExt
20/// [`Query`]: bevy_ecs::system::Query
21/// [`Children`]: super::children::Children
22/// [`BuildChildren::with_children`]: crate::child_builder::BuildChildren::with_children
23#[derive(Component, Debug, Eq, PartialEq)]
24#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
25#[cfg_attr(feature = "reflect", reflect(Component, MapEntities, PartialEq))]
26pub struct Parent(pub(crate) Entity);
27
28impl Parent {
29 /// Gets the [`Entity`] ID of the parent.
30 #[inline(always)]
31 pub fn get(&self) -> Entity {
32 self.0
33 }
34
35 /// Gets the parent [`Entity`] as a slice of length 1.
36 ///
37 /// Useful for making APIs that require a type or homogeneous storage
38 /// for both [`Children`] & [`Parent`] that is agnostic to edge direction.
39 ///
40 /// [`Children`]: super::children::Children
41 #[inline(always)]
42 pub fn as_slice(&self) -> &[Entity] {
43 std::slice::from_ref(&self.0)
44 }
45}
46
47// TODO: We need to impl either FromWorld or Default so Parent can be registered as Reflect.
48// This is because Reflect deserialize by creating an instance and apply a patch on top.
49// However Parent should only ever be set with a real user-defined entity. Its worth looking into
50// better ways to handle cases like this.
51impl FromWorld for Parent {
52 #[inline(always)]
53 fn from_world(_world: &mut World) -> Self {
54 Parent(Entity::PLACEHOLDER)
55 }
56}
57
58impl MapEntities for Parent {
59 fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
60 self.0 = entity_mapper.map_entity(self.0);
61 }
62}
63
64impl Deref for Parent {
65 type Target = Entity;
66
67 #[inline(always)]
68 fn deref(&self) -> &Self::Target {
69 &self.0
70 }
71}