Is there a way to set an entity variable in a buffer element via EntityCommandBuffer?

I have an entity that was created using EntityCommandBuffer then I want to set that entity to a variable in a buffer element. We can’t set the entity directly because it was created via EntityCommandBuffer. The entity must be set using also the EntityCommandBuffer but there’s no such method. I only see AppendToBuffer(). What I want is something like SetBufferElement(int sortKey, int index, T element).

// Say this is the buffer element
struct MyBufferElement : IBufferElement {
    public Entity someOtherEntity;

    ... // Other variables
}

// Then somewhere along a job
public void Execute(...) {
    ...

    Entity someNewEntity = this.commandBuffer.CreateEntity(...);

    DynamicBuffer<MyBufferElement> elements = ...;

    // We can't do this because someNewEntity is created via EntityCommandBuffer
    // It's not an actual entity yet.
    MyBufferElement element = elements[someIndex];
    element.someOtherEntity = someNewEntity;
    elements[someIndex] = element;
}

Also, I want to do this in a parallel writer.

The current solution I have in mind is to create another system that listens for newly created entities (using ISystemStateComponent) and then assign them to their owning entity.

If ordering isn’t important I would just remove the existing element and use append to re-add it to end.

If you can’t use append I think you need to use Add/SetBuffer, memcpy across and just replace it. It’s not ideal.

-edit-

I agree that I think SetBufferElement would be a useful addition

-edit2-

then again, there’s no guarantee the order the buffer is the same by the time the playback occurs - this could cause some very hard to track bugs.

2 Likes

I usually have a couple of synchronous systems adjacent to an ECBSystem to process this kind of stuff. EntityManager either by ExclusiveEntityTransaction or a Bursted system is faster at this sort of thing.