IndexOutOfRangeException error for code that used to work

I’m having trouble with this code that used to work

Debug.Log($"{tileIndexStartLocal.Length} {testIndex}");
var c = tileIndexStartLocal[testIndex];
Debug.Log("test");

First output is “288 4” and I never get the “test” outputted in the console.

I get this error:

IndexOutOfRangeException: Index 4 is out of restricted IJobParallelFor range [0…3] in ReadWriteBuffer.
ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.

this happens inside an Entities.ForEach, tileIndexStartLocal is a persistent NativeArray that is set up in Update function before the Entities.ForEach. In the ForEach I only read from this array.

Anyone got any clues what’s up?

Thanks!

Please post whole related part of the job.
It feels something else is going on there.

Are you testing this single threaded, or multithreaded?

Thanks for the reply, it’s a huge job, as it’s my own custom physics system.

I’ll try creating a new system to reproduces the bug and post it here!

Here we go, this code isn’t pretty but I removed everything else, but what’s needed to get the error:

public void FixedUpdate()
{
    var stepCount = 10;
    
    TileIndexStart = new NativeArray<int>(288, Allocator.Persistent);

    JobHandle[] stepJob1Handle = new JobHandle[stepCount];
    JobHandle[] stepJob2Handle = new JobHandle[stepCount];

    for (int step = 0; step < stepCount; step++)
    {
        if (step == 0)
        {
            stepJob1Handle[step] = Dependency;
        }
        else
        {
            stepJob1Handle[step] = stepJob2Handle[step - 1];
        }
        
        var tileIndexStartLocal = TileIndexStart;

        stepJob2Handle[step] = Entities.ForEach((ref Physics p) =>
        {
            var testIndex = 4;
            Debug.Log($"{tileIndexStartLocal.Length} {testIndex}"); // 288 4
            var c = tileIndexStartLocal[testIndex]; // <- stops here
            Debug.Log("test");
        }).ScheduleParallel(stepJob1Handle[step]);
    }
    
    Dependency = stepJob2Handle[stepCount - 1];
    Dependency.Complete();
}
        }

You’re missing .WithReadOnly(tileIndexStartLocal)

2 Likes

Yay!! That’s it, now it works! Thanks a million! I wasn’t aware of WithReadOnly and this worked before with a previous version of the Entities package.