How To Instantiate An Entity In ISystem

Hey,

I’ve been trying to instantiate an entity in a script of type ISystem but whenever i reference EntityManager
or EntityCommandBuffer it gives me an error.

What am i doing wrong?

Code:

using Unity.Entities;
using Unity.Burst;

public partial class CubeSpawnerDOTS : ISystem
{
    void OnUpdate()
    {
        EntityQuery entityQuery = EntityManager.CreateEntityQuery(typeof(PlayerTag));

        CubeSpawner cubeSpawner = SystemAPI.GetSingleton<CubeSpawner>();

        EntityCommandBuffer entityCommandBuffer = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(World.Unmanaged);

        if (entityQuery.CalculateEntityCount() < 10)
        {
            entityCommandBuffer.Instantiate(cubeSpawner.Cube);
        }

    }
}

When compiled I get this error:

CS0120	An object reference is required for the non-static field, method, or property 'EntityManager.CreateEntityQuery(params ComponentType[])'

This error is raised because EntityManager is a type.

If you were using a SystemBase before this confusion comes from the fact that SystemBase has public EntityManager EntityManager; field of the identical name as the type itself, so it is super easy to confuse the two.

Solution

To access an EntityManager from an ISystem use state.EntityManager

EntityQuery entityQuery = state.EntityManager.CreateEntityQuery( typeof(PlayerTag) );

This is how this code is supposed to look like:

using Unity.Entities;

[UpdateInGroup( typeof(SimulationSystemGroup) )]
[Unity.Burst.BurstCompile]
public partial struct CubeSpawnerDOTS : ISystem
{
    [Unity.Burst.BurstCompile]
    public void OnCreate ( ref SystemState state )
    {
        state.RequireForUpdate<CubeSpawner>();
    }

    [Unity.Burst.BurstCompile]
	public void OnDestroy ( ref SystemState state )
    {
    
    }

    [Unity.Burst.BurstCompile]
	public void OnUpdate ( ref SystemState state )
    {
        var query = SystemAPI.QueryBuilder().WithAll<PlayerTag>().Build();
        if( query.CalculateEntityCount() < 10 )
        {
            var cubeSpawner = SystemAPI.GetSingleton<CubeSpawner>();
            
            // immediate instantiate:
            Entity instance = state.EntityManager.Instantiate( cubeSpawner.Cube );

            // delayed instantiate:
            //var commandBuffer = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer( state.World.Unmanaged );
            //Entity instance = commandBuffer.Instantiate( cubeSpawner.Cube );
        }
    }
}

check it

you can derive your “objects” by instantiating.