Expand description
This module contains all entity types and utilities for interacting with their ids.
§What is an Entity?
The ecs docs give an overview of what entities are and generally how to use them.
These docs provide more detail into how they actually work.
In these docs Entity and “entity id” are synonymous and refer to the Entity type, which identifies an entity.
The term “entity” used on its own refers to the “thing”/“game object” that id references.
§In this Module
This module contains four main things:
- Core ECS types like
Entity,Entities, andEntityAllocator. - Utilities for
Entityids likeMapEntities,EntityHash, andUniqueEntityVec. - Helpers for entity tasks like
EntityCloner. - Entity-related error types like
EntityNotSpawnedError.
§Entity Life Cycle
Entities have life cycles. They are created, used for a while, and eventually destroyed. Let’s start from the top:
Spawn: An entity is created.
In bevy, this is called spawning.
Most commonly, this is done through World::spawn or Commands::spawn.
This creates a fresh entity in the world and returns its Entity id, which can be used to interact with the entity it identifies.
These methods initialize the entity with a Bundle, a group of components that it starts with.
It is also possible to use World::spawn_empty or Commands::spawn_empty, which are similar but do not add any components to the entity.
In either case, the returned Entity id is used to further interact with the entity.
Update: Once an entity is created, you will need its Entity id to perform further actions on it.
This can be done through World::entity_mut and Commands::entity.
Even if you don’t store the id, you can still find the entity you spawned by searching for it in a Query.
Queries are also the primary way of interacting with an entity’s components.
You can use EntityWorldMut::remove and EntityCommands::remove to remove components,
and you can use EntityWorldMut::insert and EntityCommands::insert to insert more components.
Be aware that each entity can only have 0 or 1 values for each kind of component, so inserting a bundle may overwrite existing component values.
This can also be further configured based on the insert method.
Despawn: Despawn an entity when it is no longer needed.
This destroys it and all its components.
The entity is no longer reachable through the World, Commands, or Querys.
Note that this means an Entity id may refer to an entity that has since been despawned!
Not all Entity ids refer to active entities.
If an Entity id is used when its entity has been despawned, an EntityNotSpawnedError is emitted.
Any System could despawn any entity; even if you never share its id, it could still be despawned unexpectedly.
Your code should do its best to handle these errors gracefully.
In short:
- Entities are spawned through methods like
World::spawn, which return anEntityid for the new entity. - Once spawned, they can be accessed and modified through
Querys and other apis. - You can get the
Entityid of an entity throughQuerys, so losing anEntityid is not a problem. - Entities can have components inserted and removed via
World::entity_mutandCommands::entity. - Entities are eventually despawned, destroying the entity and causing its
Entityid to no longer refer to an entity. - Not all
Entityids point to actual entities, which makes many entity methods fallible.
§Entity Allocation
Entity spawning is actually done in two stages:
- Allocate: We generate a new valid / unique
Entity. - Spawn: We make the entity “exist” in the
World. It will show up in queries, it can have components, etc.
The reason for this split is that we need to be able to allocate entity ids concurrently, whereas spawning requires unique (non-concurrent) access to the world.
An Entity therefore goes through the following lifecycle:
- Unallocated (and “valid”): Only the allocator has any knowledge of this
Entity, but it could be spawned, theoretically. - Allocated (and “valid”): The allocator has handed out the
Entity, but it is not yet spawned. - Spawned: The entity now “exists” in the
World. It will show up in queries, it can have components, etc. - Despawned: The entity no longer “exist” in the
World. - Freed (and “invalid”): The
Entityis returned to the allocator. TheEntity::generationis bumped, which makes all existingEntityreferences with the previous generation “invalid”.
Note that by default, most spawn and despawn APIs handle the Entity allocation and freeing process for developers.
Modules§
- hash_
map - Contains the
EntityHashMaptype, aHashMappre-configured to useEntityHashhashing. - hash_
set - Contains the
EntityHashSettype, aHashSetpre-configured to useEntityHashhashing. - index_
map - Contains the
EntityIndexMaptype, anIndexMappre-configured to useEntityHashhashing. - index_
set - Contains the
EntityIndexSettype, aIndexSetpre-configured to useEntityHashhashing. - unique_
array - A wrapper around entity arrays with a uniqueness invariant.
- unique_
slice - A wrapper around entity slices with a uniqueness invariant.
- unique_
vec - A wrapper around entity
Vecs with a uniqueness invariant.
Structs§
- Alloc
Entities Iterator - An
Iteratorreturning a sequence of uniqueEntityvalues fromEntities. Dropping this will still retain the entities as allocated; this is effectively a leak. To prevent this, ensure the iterator is exhausted before dropping it. - Component
Clone Ctx - Context for component clone handlers.
- Entities
Entitiestracks all knownEntityIndexs and their metadata. This is like a base table of information all entities have.- Entity
- 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 theWorld. For more information about entities, their ids, and how to use them, see the module docs. - Entity
Allocator - Allocates
Entityids uniquely. This is used inWorld::spawn_atandWorld::despawn_no_freeto track entity ids no longer in use. Allocating is fully concurrent and can be done from multiple threads. - Entity
Cloner - A configuration determining how to clone entities. This can be built using
EntityCloner::build_opt_out/opt_in, which returns anEntityClonerBuilder. - Entity
Cloner Builder - A builder for configuring
EntityCloner. SeeEntityClonerfor more information. - Entity
Generation - This tracks different versions or generations of an
EntityIndex. Importantly, this can wrap, meaning each generation is not necessarily unique perEntityIndex. - Entity
Hash - A
BuildHasherthat results in aEntityHasher. - Entity
Hash Map - A
HashMappre-configured to useEntityHashhashing. - Entity
Hash Set - A
HashSetpre-configured to useEntityHashhashing. - Entity
Hasher - A very fast hash that is only designed to work on generational indices
like
Entity. It will panic if attempting to hash a type containing non-u64 fields. - Entity
Index - This represents the index of an
Entitywithin theEntitiesarray. This is a lighter weight version ofEntity. - Entity
Index Map - A
IndexMappre-configured to useEntityHashhashing. - Entity
Index Set - An
IndexSetpre-configured to useEntityHashhashing. - Entity
Location - A location of an entity in an archetype.
- Entity
Valid ButNot Spawned Error - An error that occurs when a specified
Entityis certain to be valid and is expected to be spawned but is spawned. This includes when anEntityIndexis requested but is not spawned, since each index always corresponds to exactly one valid entity. - Invalid
Entity Error - An error that occurs when a specified
Entitydoes not exist in the entity id space. See module docs for more about entity validity. - OptIn
- Generic for
EntityClonerBuilderthat makes the cloner try to clone every component that was explicitly allowed from the source entity, for example by using theallowmethod. - OptOut
- Generic for
EntityClonerBuilderthat makes the cloner try to clone every component from the source entity except for components that were explicitly denied, for example by using thedenymethod. - Scene
Entity Mapper - A wrapper for
EntityHashMap<Entity>, augmenting it with the ability to allocate newEntityreferences in a destination world. These newly allocated references are guaranteed to never point to any living entity in that world. - Source
Component - Provides read access to the source component (the component being cloned) in a
ComponentCloneFn. - Unique
Entity Equivalent Array - An array that contains only unique entities.
- Unique
Entity Equivalent Slice - A slice that contains only unique entities.
- Unique
Entity Equivalent Vec - A
Vecthat contains only unique entities. - Unique
Entity Iter - An iterator that yields unique entities.
Enums§
- Entity
NotSpawned Error - An error that occurs when a specified
Entityis expected to be valid and spawned but is not. Represents an error of eitherInvalidEntityError(when the entity is invalid) orEntityValidButNotSpawnedError(when theEntityGenerationis correct but theEntityIndexis not spawned). - Spawn
Error - An error that occurs when a specified
Entitycan not be spawned.
Traits§
- Contains
Entity - A trait for types that contain an
Entity. - Entity
Equivalent - A trait for types that represent an
Entity. - Entity
Mapper - An implementor of this trait knows how to map an
Entityinto anotherEntity. - Entity
Set - A set of unique entities.
- Entity
SetIterator - An iterator over a set of unique entities.
- From
Entity SetIterator - Conversion from an
EntitySetIterator. - MapEntities
- Operation to map all contained
Entityfields in a type to new values.
Type Aliases§
- Unique
Entity Array - An array that contains only unique
Entity. - Unique
Entity Slice - A slice that contains only unique
Entity. - Unique
Entity Vec - A
Vecthat contains only uniqueEntity.
Derive Macros§
- MapEntities
- Implement the
MapEntitiestrait.