Creating a new entity that has a reference to itself from a job

Task:

I would like to dynamically create entities, and these entities should have an Entity reference to themselves (the reason for this is that the entity topology is hierarchical, and entities can create children with links back to their parents). I could use a special empty component type for this but it doesn’t help me fill in the TransformParent component I’m using for my hierarchy.

Problem:

  1. In a job, you can’t access the entity manager. Entities can be created using command buffers, which create the entity later on. But since you don’t have a reference to the as-yet non-existent entity, you can’t set the entity up with a reference to itself. That all makes sense and doesn’t seem solvable without some kind of fairly edge case new API.
  2. I can’t actually think of a way to tie up an entity reference from a system on e.g. the first cycle after the entity is created. Any ideas?

Current solution:

Do this in the main thread as part of a ComponentSystem, as you can access the entity manager from there and use the entity reference sent back from CreateEntity as your reference.

phase 1: create entity with “AssignSelf” component tag
phase 2: loop all entities with “AssignSelf”, add “EntityReference” to self, remove “AssignSelf”

you need a barrier system, execute phase 1 before the barrier and phase 2 after the barrier

Thanks. I guess I don’t know where the entity reference you mention would come from though. Can you get a reference to an entity from a group index? I would love that.
e.g.

struct InjectedGroup{
  public ComponentDataArray<Transform> transforms;
  public int Length;
}

[Inject] InjectedGroup group;

protected void OnUpdate()
{
  for(int i = 0; i < group.Length; i++)
  {
    Entity entity = group.GetEntity(i); // n.b. this does not exist to my knowledge
  }
}

From the documentation

// Sometimes it is necessary to not only access the components
// but also the Entity ID.
public EntityArray Entities;

1 Like

Amazing. Thank you!