Skip to main content

Entity

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

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

Creates a new instance with the given index and generation.

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>

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

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

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>

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

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

Equivalent to self.index().index(). See Self::index for details.

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 Clone for Entity

§

fn clone(&self) -> Entity

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl ContainsEntity for Entity

§

fn entity(&self) -> Entity

Returns the contained entity.
§

impl ContiguousQueryData for Entity

§

type Contiguous<'w, 's> = &'w [Entity]

Item returned by [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>

Fetch [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.

This takes the format: {index}v{generation}.

For Entity::PLACEHOLDER, this outputs PLACEHOLDER.

For a unique u64 representation, use Entity::to_bits.

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

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.

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl From<RemovedComponentEntity> for Entity

§

fn from(value: RemovedComponentEntity) -> Entity

Converts to this type from the input type.
§

impl FromTemplate for Entity

§

type Template = EntityTemplate

The Template for this type.
§

impl Hash for Entity

§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
§

impl MapEntities for Entity

§

fn map_entities<E>(&mut self, entity_mapper: &mut E)
where E: EntityMapper,

Updates all Entity references stored inside using entity_mapper. Read more
§

impl Ord for Entity

§

fn cmp(&self, other: &Entity) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
§

impl PartialEq for Entity

§

fn eq(&self, other: &Entity) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl PartialOrd for Entity

§

fn partial_cmp(&self, other: &Entity) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

impl QueryData for Entity

§

const IS_READ_ONLY: bool = true

True if this query is read-only and may not perform mutable access.
§

const IS_ARCHETYPAL: bool = true

Returns true if (and only if) this query data relies strictly on archetypes to limit which entities are accessed by the Query. Read more
§

type ReadOnly = Entity

The read-only variant of this [QueryData], which satisfies the [ReadOnlyQueryData] trait.
§

type Item<'w, 's> = Entity

The item returned by this [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,

This function manually implements subtyping for the query items.
§

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>>

Fetch 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<'_>>

Returns an iterator over the access needed by [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, )

Offers additional access above what we requested in 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

§

type SourceIter<'a> = IntoIter<Entity>

The type of iterator returned by the iter method. Read more
§

fn new() -> Entity

Creates a new empty instance.
§

fn reserve(&mut self, _: usize)

Reserves capacity for at least additional more entities to be inserted. Read more
§

fn with_capacity(_capacity: usize) -> Entity

Returns an instance with the given pre-allocated entity capacity. Read more
§

fn add(&mut self, entity: Entity) -> bool

Adds the given entity to the collection. Read more
§

fn remove(&mut self, entity: Entity) -> bool

Removes the given entity from the collection. Read more
§

fn iter(&self) -> <Entity as RelationshipSourceCollection>::SourceIter<'_>

Iterates all entities in the collection.
§

fn len(&self) -> usize

Returns the current length of the collection.
§

fn clear(&mut self)

Clears the collection.
§

fn shrink_to_fit(&mut self)

Attempts to save memory by shrinking the capacity to fit the current length. Read more
§

fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>)

Add multiple entities to collection at once. Read more
§

fn source_to_remove_before_add(&self) -> Option<Entity>

For one-to-one relationships, returns the entity that should be removed before adding a new one. Returns None for one-to-many relationships or when no entity needs to be removed.
§

fn is_empty(&self) -> bool

Returns true if the collection contains no entities.
§

impl ReleaseStateQueryData for Entity

§

fn release_state<'w>( item: <Entity as QueryData>::Item<'w, '_>, ) -> <Entity as QueryData>::Item<'w, 'static>

Releases the borrow from the query state by converting an item to have a 'static state lifetime.
§

impl SparseSetIndex for Entity

§

fn sparse_set_index(&self) -> usize

Gets the sparse set index corresponding to this instance.
§

fn get_sparse_set_index(value: usize) -> Entity

Creates a new instance of this type with the specified index.
§

impl WorldEntityFetch for Entity

§

type Ref<'w> = EntityRef<'w>

The read-only reference type returned by [WorldEntityFetch::fetch_ref].
§

type Mut<'w> = EntityWorldMut<'w>

The mutable reference type returned by [WorldEntityFetch::fetch_mut].
§

type DeferredMut<'w> = EntityMut<'w>

The mutable reference type returned by [WorldEntityFetch::fetch_deferred_mut], but without structural mutability.
§

unsafe fn fetch_ref( self, cell: UnsafeWorldCell<'_>, ) -> Result<<Entity as WorldEntityFetch>::Ref<'_>, EntityNotSpawnedError>

Returns read-only reference(s) to the entities with the given Entity IDs, as determined by self. Read more
§

unsafe fn fetch_mut( self, cell: UnsafeWorldCell<'_>, ) -> Result<<Entity as WorldEntityFetch>::Mut<'_>, EntityMutableFetchError>

Returns mutable reference(s) to the entities with the given Entity IDs, as determined by self. Read more
§

unsafe fn fetch_deferred_mut( self, cell: UnsafeWorldCell<'_>, ) -> Result<<Entity as WorldEntityFetch>::DeferredMut<'_>, EntityMutableFetchError>

Returns mutable reference(s) to the entities with the given Entity IDs, as determined by self, but without structural mutability. Read more
§

impl WorldQuery for Entity

§

const IS_DENSE: bool = true

Returns true if (and only if) every table of every archetype matched by this fetch contains all of the matched components. Read more
§

type Fetch<'w> = ()

Per archetype/table state retrieved by this [WorldQuery] to compute Self::Item for each entity.
§

type State = ()

State used to construct a 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,

This function manually implements subtyping for the query fetches.
§

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>

Creates a new instance of 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, )

Adjusts internal state to account for the next [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, )

Adjusts internal state to account for the next [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, )

Adds any component accesses to the current entity used by this [WorldQuery] to access. Read more
§

fn init_state(_world: &mut World)

Creates and initializes a State for this [WorldQuery] type.
§

fn get_state(_components: &Components) -> Option<()>

Attempts to initialize a State for this [WorldQuery] type using read-only access to [Components].
§

fn matches_component_set( _state: &<Entity as WorldQuery>::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool

Returns true if this query matches a set of components. Otherwise, returns false. Read more
§

fn init_nested_access( _state: &Self::State, _system_name: Option<&str>, _component_access_set: &mut FilteredAccessSet, _world: UnsafeWorldCell<'_>, )

Adds any component accesses to other entities used by this [WorldQuery]. Read more
§

fn update_archetypes(_state: &mut Self::State, _world: UnsafeWorldCell<'_>)

Called when the query state is updating its archetype cache. This can be used by nested queries to update their internal archetype caches.
§

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§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
§

impl<T> DynEq for T
where T: Any + Eq,

§

fn dyn_eq(&self, other: &(dyn DynEq + 'static)) -> bool

This method tests for self and other values to be equal. Read more
§

impl<T> DynHash for T
where T: DynEq + Hash,

§

fn dyn_hash(&self, state: &mut dyn Hasher)

Feeds this value into the given Hasher.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> IntoResult<T> for T

§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> ConditionalSend for T
where T: Send,