(Solved) Simple job using EntityCommandBuffer breaks when 730 entities are processed

I am getting different errors after 730 entities with archetype exist in the world. 729 Entities works.
Here are some of the errors, whichever one shows up is seemingly random.

ArgumentException: All entities passed to EntityManager must exist. One of the entities has already been destroyed or was never created.

Assertion failure. Value was False
Expected: True

Assertion failure. Values are not equal.
Expected: 1 == 2

ArgumentException: Object reference not set to an instance of an object

ArgumentException: Invalid command buffer

public class SelectEntitySystem : JobComponentSystem
{
    struct RemoveSelectionsJob : IJobForEachWithEntity<Selected>
    {
        [ReadOnly] public EntityCommandBuffer buffer;
        public void Execute(Entity entity, int index, [ReadOnly] ref Selected selected)
        {
            buffer.RemoveComponent<Selected>(entity);
        }
    }

    private EntityCommandBufferSystem bufferSystem;

    protected override void OnCreateManager()
    {
        bufferSystem = World.Active.GetExistingSystem<EntityCommandBufferSystem>();
    }


    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        JobHandle combinedInputDeps = inputDeps;
        if (Input.GetMouseButtonDown(1))
        {
            // Remove all previous selections
            EntityCommandBuffer unselectBuffer = bufferSystem.CreateCommandBuffer();
            JobHandle unselect = new RemoveSelectionsJob() { buffer = unselectBuffer }.Schedule(this, inputDeps);
            bufferSystem.AddJobHandleForProducer(unselect);
            combinedInputDeps = JobHandle.CombineDependencies(inputDeps, unselect);
        }

        return combinedInputDeps;
    }
}

Dunno if this is what is causing it, but you probably want to use a EntityCommandBuffer.Concurrent when doing an IJobForEach.

2 Likes

I’m pretty sure RemoveSelectionsJob.buffer should not be ReadOnly, and should also be of type EntityCommandBuffer.Concurrent.

1 Like

You need to use concurrent command buffer:
[ReadOnly] public EntityCommandBuffer.Concurrent buffer;
EntityCommandBuffer unselectBuffer = bufferSystem.CreateCommandBuffer().ToConcurrent();

Jobs are running for each chunk at the same time, not concurrent command buffer worked fine when you have one chunk, but when you have more than one chunk you get the error.
In your case, one chunk can contain 729 entities, and with 730 entities you have two chunks.

1 Like

Thank you, guys. I did not realize the buffer needed to be Concurrent in IJobForEach. On another note, the code as-is worked by scheduling the job with ScheduleSingle.

ScheduleSingle is run the job in a single thread, so you don’t have a problem with parallel access from the other threads.