Add components to an entity
To add components to an entity, use the EntityManager for the world that the entity is in. You can add components to an individual entity, or to several entities at the same time.
Note
Adding a component to an entity is a structural change which means that the entity moves to a different archetype chunk. Fore more information, refer to Use entity command buffer for structural changes.
Add a component to a single entity
The following code sample creates a new entity then adds a component to the entity from the main thread.
public partial struct AddComponentToSingleEntitySystemExample : ISystem
{
public void OnCreate(ref SystemState state)
{
var entity = state.EntityManager.CreateEntity();
state.EntityManager.AddComponent<Rotation>(entity);
}
}
Add a component to multiple entities
The following code sample gets every entity with an attached ComponentA component and adds a ComponentB component to them from the main thread.
struct ComponentA : IComponentData {}
struct ComponentB : IComponentData {}
public partial struct AddComponentToMultipleEntitiesSystemExample : ISystem
{
public void OnCreate(ref SystemState state)
{
var query = state.GetEntityQuery(typeof(ComponentA));
state.EntityManager.AddComponent<ComponentB>(query);
}
}