Struct Entity
pub struct Entity { /* private fields */ }Expand description
Unique identifier for an entity in a World.
Note that this is just an id, not the entity itself.
Further, the entity this id refers to may no longer exist in the World.
For more information about entities, their ids, and how to use them, see the module docs.
§Aliasing
Once an entity is despawned, it ceases to exist.
However, its Entity id is still present, and may still be contained in some data.
This becomes problematic because it is possible for a later entity to be spawned at the exact same id!
If this happens, which is rare but very possible, it will be logged.
Aliasing can happen without warning.
Holding onto a Entity id corresponding to an entity well after that entity was despawned can cause un-intuitive behavior for both ordering, and comparing in general.
To prevent these bugs, it is generally best practice to stop holding an Entity or [EntityGeneration] value as soon as you know it has been despawned.
If you must do otherwise, do not assume the Entity id corresponds to the same entity it originally did.
See [EntityGeneration]’s docs for more information about aliasing and why it occurs.
§Stability warning
For all intents and purposes, Entity should be treated as an opaque identifier. The internal bit
representation is liable to change from release to release as are the behaviors or performance
characteristics of any of its trait implementations (i.e. Ord, Hash, etc.). This means that changes in
Entity’s representation, though made readable through various functions on the type, are not considered
breaking changes under SemVer.
In particular, directly serializing with Serialize and Deserialize make zero guarantee of long
term wire format compatibility. Changes in behavior will cause serialized Entity values persisted
to long term storage (i.e. disk, databases, etc.) will fail to deserialize upon being updated.
§Usage
This data type is returned by iterating a Query that has Entity as part of its query fetch type parameter (learn more).
It can also be obtained by calling EntityCommands::id or EntityWorldMut::id.
fn setup(mut commands: Commands) {
// Calling `spawn` returns `EntityCommands`.
let entity = commands.spawn(SomeComponent).id();
}
fn exclusive_system(world: &mut World) {
// Calling `spawn` returns `EntityWorldMut`.
let entity = world.spawn(SomeComponent).id();
}It can be used to refer to a specific entity to apply EntityCommands, or to call Query::get (or similar methods) to access its components.
fn dispose_expired_food(mut commands: Commands, query: Query<Entity, With<Expired>>) {
for food_entity in &query {
commands.entity(food_entity).despawn();
}
}Implementations§
§impl Entity
impl Entity
pub const PLACEHOLDER: Entity
pub const PLACEHOLDER: Entity
An entity ID with a placeholder value. This may or may not correspond to an actual entity, and should be overwritten by a new value before being used.
§Examples
Initializing a collection (e.g. array or Vec) with a known size:
// Create a new array of size 10 filled with invalid entity ids.
let mut entities: [Entity; 10] = [Entity::PLACEHOLDER; 10];
// ... replace the entities with valid ones.Deriving [Reflect] for a component that has an Entity field:
#[derive(Reflect, Component)]
#[reflect(Component)]
pub struct MyStruct {
pub entity: Entity,
}
impl FromWorld for MyStruct {
fn from_world(_world: &mut World) -> Self {
Self {
entity: Entity::PLACEHOLDER,
}
}
}pub const fn from_index_and_generation(
index: EntityIndex,
generation: EntityGeneration,
) -> Entity
pub const fn from_index_and_generation( index: EntityIndex, generation: EntityGeneration, ) -> Entity
Creates a new instance with the given index and generation.
pub const fn from_index(index: EntityIndex) -> Entity
pub const fn from_index(index: EntityIndex) -> Entity
Creates a new entity ID with the specified index and an unspecified generation.
§Note
Spawning a specific entity value is rarely the right choice. Most apps should favor
Commands::spawn. This method should generally
only be used for sharing entities across apps, and only when they have a scheme
worked out to share an index space (which doesn’t happen by default).
In general, one should not try to synchronize the ECS by attempting to ensure that
Entity lines up between instances, but instead insert a secondary identifier as
a component.
pub const fn from_raw_u32(index: u32) -> Option<Entity>
pub const fn from_raw_u32(index: u32) -> Option<Entity>
This is equivalent to from_index except that it takes a u32 instead of an [EntityIndex].
Returns None if the index is u32::MAX.
pub const fn to_bits(self) -> u64
pub const fn to_bits(self) -> u64
Convert to a form convenient for passing outside of rust.
Only useful for identifying entities within the same instance of an application. Do not use for serialization between runs.
No particular structure is guaranteed for the returned bits.
pub const fn from_bits(bits: u64) -> Entity
pub const fn from_bits(bits: u64) -> Entity
Reconstruct an Entity previously destructured with Entity::to_bits.
Only useful when applied to results from to_bits in the same instance of an application.
§Panics
This method will likely panic if given u64 values that did not come from Entity::to_bits.
pub const fn try_from_bits(bits: u64) -> Option<Entity>
pub const fn try_from_bits(bits: u64) -> Option<Entity>
Reconstruct an Entity previously destructured with Entity::to_bits.
Only useful when applied to results from to_bits in the same instance of an application.
This method is the fallible counterpart to Entity::from_bits.
pub const fn index(self) -> EntityIndex
pub const fn index(self) -> EntityIndex
Return a transiently unique identifier.
See also [EntityIndex].
No two simultaneously-live entities share the same index, but dead entities’ indices may collide with both live and dead entities. Useful for compactly representing entities within a specific snapshot of the world, such as when serializing.
pub const fn index_u32(self) -> u32
pub const fn index_u32(self) -> u32
Equivalent to self.index().index(). See Self::index for details.
pub const fn generation(self) -> EntityGeneration
pub const fn generation(self) -> EntityGeneration
Returns the generation of this Entity’s index. The generation is incremented each time an entity with a given index is despawned. This serves as a “count” of the number of times a given index has been reused (index, generation) pairs uniquely identify a given Entity.
Trait Implementations§
§impl ContiguousQueryData for Entity
impl ContiguousQueryData for Entity
§type Contiguous<'w, 's> = &'w [Entity]
type Contiguous<'w, 's> = &'w [Entity]
ContiguousQueryData::fetch_contiguous].
Represents a contiguous chunk of memory.§unsafe fn fetch_contiguous<'w, 's>(
_state: &'s <Entity as WorldQuery>::State,
_fetch: &mut <Entity as WorldQuery>::Fetch<'w>,
entities: &'w [Entity],
) -> <Entity as ContiguousQueryData>::Contiguous<'w, 's>
unsafe fn fetch_contiguous<'w, 's>( _state: &'s <Entity as WorldQuery>::State, _fetch: &mut <Entity as WorldQuery>::Fetch<'w>, entities: &'w [Entity], ) -> <Entity as ContiguousQueryData>::Contiguous<'w, 's>
ContiguousQueryData::Contiguous] which represents a contiguous chunk of memory (e.g., an array) in the current [Table].
This must always be called after [WorldQuery::set_table]. Read more§impl Debug for Entity
Outputs the short entity identifier, including the index and generation.
impl Debug for Entity
Outputs the short entity identifier, including the index and generation.
This takes the format: {index}v{generation}.
For Entity::PLACEHOLDER, this outputs PLACEHOLDER.
For a unique u64 representation, use Entity::to_bits.
§impl Display for Entity
Outputs the short entity identifier, including the index and generation.
impl Display for Entity
Outputs the short entity identifier, including the index and generation.
This takes the format: {index}v{generation}.
For Entity::PLACEHOLDER, this outputs PLACEHOLDER.
§impl MapEntities for Entity
impl MapEntities for Entity
§fn map_entities<E>(&mut self, entity_mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(&mut self, entity_mapper: &mut E)where
E: EntityMapper,
§impl Ord for Entity
impl Ord for Entity
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
§impl PartialOrd for Entity
impl PartialOrd for Entity
§impl QueryData for Entity
impl QueryData for Entity
§const IS_READ_ONLY: bool = true
const IS_READ_ONLY: bool = true
§const IS_ARCHETYPAL: bool = true
const IS_ARCHETYPAL: bool = true
§type ReadOnly = Entity
type ReadOnly = Entity
QueryData], which satisfies the [ReadOnlyQueryData] trait.§type Item<'w, 's> = Entity
type Item<'w, 's> = Entity
WorldQuery]
This will be the data retrieved by the query,
and is visible to the end user when calling e.g. Query<Self>::get.§fn shrink<'wlong, 'wshort, 's>(
item: <Entity as QueryData>::Item<'wlong, 's>,
) -> <Entity as QueryData>::Item<'wshort, 's>where
'wlong: 'wshort,
fn shrink<'wlong, 'wshort, 's>(
item: <Entity as QueryData>::Item<'wlong, 's>,
) -> <Entity as QueryData>::Item<'wshort, 's>where
'wlong: 'wshort,
§unsafe fn fetch<'w, 's>(
_state: &'s <Entity as WorldQuery>::State,
_fetch: &mut <Entity as WorldQuery>::Fetch<'w>,
entity: Entity,
_table_row: TableRow,
) -> Option<<Entity as QueryData>::Item<'w, 's>>
unsafe fn fetch<'w, 's>( _state: &'s <Entity as WorldQuery>::State, _fetch: &mut <Entity as WorldQuery>::Fetch<'w>, entity: Entity, _table_row: TableRow, ) -> Option<<Entity as QueryData>::Item<'w, 's>>
Self::Item for either the given entity in the current [Table],
or for the given entity in the current [Archetype]. This must always be called after
[WorldQuery::set_table] with a table_row in the range of the current [Table] or after
[WorldQuery::set_archetype] with an entity in the current archetype.
Accesses components registered in [WorldQuery::update_component_access]. Read more§fn iter_access(
_state: &<Entity as WorldQuery>::State,
) -> impl Iterator<Item = EcsAccessType<'_>>
fn iter_access( _state: &<Entity as WorldQuery>::State, ) -> impl Iterator<Item = EcsAccessType<'_>>
QueryData::fetch]. Access conflicts are usually
checked in [WorldQuery::update_component_access], but in certain cases this method can be useful to implement
a way of checking for access conflicts in a non-allocating way.§fn provide_extra_access(
_state: &mut Self::State,
_access: &mut Access,
_available_access: &Access,
)
fn provide_extra_access( _state: &mut Self::State, _access: &mut Access, _available_access: &Access, )
update_component_access.
Implementations may add additional access that is a subset of available_access
and does not conflict with anything in access,
and must update access to include that access. Read more§impl RelationshipSourceCollection for Entity
impl RelationshipSourceCollection for Entity
§type SourceIter<'a> = IntoIter<Entity>
type SourceIter<'a> = IntoIter<Entity>
iter method. Read more§fn reserve(&mut self, _: usize)
fn reserve(&mut self, _: usize)
additional more entities to be inserted. Read more§fn with_capacity(_capacity: usize) -> Entity
fn with_capacity(_capacity: usize) -> Entity
capacity. Read more§fn remove(&mut self, entity: Entity) -> bool
fn remove(&mut self, entity: Entity) -> bool
entity from the collection. Read more§fn iter(&self) -> <Entity as RelationshipSourceCollection>::SourceIter<'_>
fn iter(&self) -> <Entity as RelationshipSourceCollection>::SourceIter<'_>
§fn shrink_to_fit(&mut self)
fn shrink_to_fit(&mut self)
§fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>)
fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>)
§fn source_to_remove_before_add(&self) -> Option<Entity>
fn source_to_remove_before_add(&self) -> Option<Entity>
None for one-to-many relationships or when no entity needs to be removed.§impl ReleaseStateQueryData for Entity
impl ReleaseStateQueryData for Entity
§fn release_state<'w>(
item: <Entity as QueryData>::Item<'w, '_>,
) -> <Entity as QueryData>::Item<'w, 'static>
fn release_state<'w>( item: <Entity as QueryData>::Item<'w, '_>, ) -> <Entity as QueryData>::Item<'w, 'static>
'static state lifetime.§impl SparseSetIndex for Entity
impl SparseSetIndex for Entity
§fn sparse_set_index(&self) -> usize
fn sparse_set_index(&self) -> usize
§fn get_sparse_set_index(value: usize) -> Entity
fn get_sparse_set_index(value: usize) -> Entity
§impl WorldEntityFetch for Entity
impl WorldEntityFetch for Entity
§type Ref<'w> = EntityRef<'w>
type Ref<'w> = EntityRef<'w>
WorldEntityFetch::fetch_ref].§type Mut<'w> = EntityWorldMut<'w>
type Mut<'w> = EntityWorldMut<'w>
WorldEntityFetch::fetch_mut].§type DeferredMut<'w> = EntityMut<'w>
type DeferredMut<'w> = EntityMut<'w>
WorldEntityFetch::fetch_deferred_mut],
but without structural mutability.§unsafe fn fetch_ref(
self,
cell: UnsafeWorldCell<'_>,
) -> Result<<Entity as WorldEntityFetch>::Ref<'_>, EntityNotSpawnedError>
unsafe fn fetch_ref( self, cell: UnsafeWorldCell<'_>, ) -> Result<<Entity as WorldEntityFetch>::Ref<'_>, EntityNotSpawnedError>
§impl WorldQuery for Entity
impl WorldQuery for Entity
§const IS_DENSE: bool = true
const IS_DENSE: bool = true
§type Fetch<'w> = ()
type Fetch<'w> = ()
WorldQuery] to compute Self::Item for each entity.§type State = ()
type State = ()
Self::Fetch. This will be cached inside QueryState,
so it is best to move as much data / computation here as possible to reduce the cost of
constructing Self::Fetch.§fn shrink_fetch<'wlong, 'wshort>(
_: <Entity as WorldQuery>::Fetch<'wlong>,
) -> <Entity as WorldQuery>::Fetch<'wshort>where
'wlong: 'wshort,
fn shrink_fetch<'wlong, 'wshort>(
_: <Entity as WorldQuery>::Fetch<'wlong>,
) -> <Entity as WorldQuery>::Fetch<'wshort>where
'wlong: 'wshort,
§unsafe fn init_fetch<'w, 's>(
_world: UnsafeWorldCell<'w>,
_state: &'s <Entity as WorldQuery>::State,
_last_run: Tick,
_this_run: Tick,
) -> <Entity as WorldQuery>::Fetch<'w>
unsafe fn init_fetch<'w, 's>( _world: UnsafeWorldCell<'w>, _state: &'s <Entity as WorldQuery>::State, _last_run: Tick, _this_run: Tick, ) -> <Entity as WorldQuery>::Fetch<'w>
Self::Fetch,
by combining data from the World with the cached Self::State.
Readonly accesses resources registered in [WorldQuery::update_component_access]. Read more§unsafe fn set_archetype<'w, 's>(
_fetch: &mut <Entity as WorldQuery>::Fetch<'w>,
_state: &'s <Entity as WorldQuery>::State,
_archetype: &'w Archetype,
_table: &Table,
)
unsafe fn set_archetype<'w, 's>( _fetch: &mut <Entity as WorldQuery>::Fetch<'w>, _state: &'s <Entity as WorldQuery>::State, _archetype: &'w Archetype, _table: &Table, )
Archetype]. This will always be called on
archetypes that match this [WorldQuery]. Read more§unsafe fn set_table<'w, 's>(
_fetch: &mut <Entity as WorldQuery>::Fetch<'w>,
_state: &'s <Entity as WorldQuery>::State,
_table: &'w Table,
)
unsafe fn set_table<'w, 's>( _fetch: &mut <Entity as WorldQuery>::Fetch<'w>, _state: &'s <Entity as WorldQuery>::State, _table: &'w Table, )
Table]. This will always be called on tables
that match this [WorldQuery]. Read more§fn update_component_access(
_state: &<Entity as WorldQuery>::State,
_access: &mut FilteredAccess,
)
fn update_component_access( _state: &<Entity as WorldQuery>::State, _access: &mut FilteredAccess, )
§fn init_state(_world: &mut World)
fn init_state(_world: &mut World)
State for this [WorldQuery] type.§fn matches_component_set(
_state: &<Entity as WorldQuery>::State,
_set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool
fn matches_component_set( _state: &<Entity as WorldQuery>::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool
§fn init_nested_access(
_state: &Self::State,
_system_name: Option<&str>,
_component_access_set: &mut FilteredAccessSet,
_world: UnsafeWorldCell<'_>,
)
fn init_nested_access( _state: &Self::State, _system_name: Option<&str>, _component_access_set: &mut FilteredAccessSet, _world: UnsafeWorldCell<'_>, )
WorldQuery]. Read more§fn update_archetypes(_state: &mut Self::State, _world: UnsafeWorldCell<'_>)
fn update_archetypes(_state: &mut Self::State, _world: UnsafeWorldCell<'_>)
impl ArchetypeQueryData for Entity
impl Copy for Entity
impl EntityEquivalent for Entity
impl Eq for Entity
impl IterQueryData for Entity
impl ReadOnlyQueryData for Entity
impl SingleEntityQueryData for Entity
Auto Trait Implementations§
impl Freeze for Entity
impl RefUnwindSafe for Entity
impl Send for Entity
impl Sync for Entity
impl Unpin for Entity
impl UnsafeUnpin for Entity
impl UnwindSafe for Entity
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
§impl<T> DynEq for T
impl<T> DynEq for T
§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.