Skip to content

Reverse One-To-Many Relationship

What

When an object or entity has a relationship to multiple other objects / entities. For example, a Province has multiple Cities. An Army has multiple Units, etc...

Why

Storing these relationship requires a list from the parent object to the children. Processing them is often sequential, or hard to parallelise.

How

An example of this pattern as a ``MonoBehaviour```

public class Dad: MonoBehaviour {
    public Son[] sons;
    public void Update() {
        foreach (var son in sons) {
            Compute(son);
        }
    }
    private void Compute(Son son);
}
Could be refactored to a Job

internal partial struct DadAndSonJob : IJobEntity {
    [ReadOnly]
    public ComponentLookup<Dad> dads;
    private void Execute(in DadRef dadRef, ref Son son) {
        Compute(dads[dadRef.Vale], ref son);
    }
    private static void Compute(in Dad dad, ref Son son);
}

new DadAndSonJob{
    dads = SystemAPI.GetComponentLookup<Dad>(readonly: true),
}.ScheduleParalell();