docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    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.

    Adding a component to an entity is a structural change which means that the entity moves to a different chunk. This means that you can't directly add components to an entity from a job. Instead, you must use an EntityCommandBuffer to record your intention to add components later.

    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);
        }
    }
    

    Additional resources

    • EntityManager.AddComponent
    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)