How to iterate over all other ComponentDatas in a job?

Hi,
I’m trying to create a basic flocking behaviour in the ECS & Job System.
However, I can’t figure out, how I can use all ComponentDatas of one type in a job.

This is my ‘Boid’ Data:

[System.Serializable]
public struct Boid : IComponentData
{

    public Vector3 position;
    public Vector3 direction;

}

This is my JobComponentSystem:

public class BoidSystem : JobComponentSystem
{

    struct BoidCalculationJob : IJobProcessComponentData<Boid>
    {
        public float deltaTime;

        public void Execute(ref Boid data)
        {           
            // I WANT TO ITERATE OVER ALL BOIDS HERE TO DO CALCULATIONS BASED ON THE DATA OF OTHER BOIDS
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        Debug.Log(boidGroup.boids[0]);
        var job = new BoidCalculationJob()
        {
            deltaTime = Time.deltaTime
        };
        return job.Schedule(this, 64, inputDeps);
    }

}

I already tried to add a ComponentDataArray to the BoidCalculationJob struct, but however I tried it, it resulted in errors.
So, how do I pass or access all Boids to the Job?

This code will do the job

public class BoidSystem : JobComponentSystem {
    struct BoidCalculationJob : IJobParallelFor {
        public float deltaTime;
        //[WriteOnly] // if you  only write
        //[ReadOnly] // if you only read     
        //[NativeDisableParallelForRestriction] // required if you write
        public ComponentDataArray<Boid> boids;
        public void Execute(int index) {
            // do what you wanna do ...    boids[index]
        }
    }

    struct BoidsData {
        public int Length; //is determined internally by unity
        //[WriteOnly] // if you only write
        //[ReadOnly] // if you only read
        public ComponentDataArray<Boid> boids;
    }
    [Inject] BoidsData boidData;
    protected override JobHandle OnUpdate(JobHandle inputDeps) {

        var job = new BoidCalculationJob() {
            deltaTime = Time.deltaTime,
            boids = boidData.boids
        };
        return job.Schedule(boidData.Length, 1, inputDeps);
    }
}
1 Like

Thank you for your help! It’s working now.

1 Like