Dynamic buffer index out of range error

Hi all, in one of my job systems I have a simple that job that collects entities and assigns them to a dynamic buffer if they haven’t already:

    public struct AssignProjectileToBuffer : IJobForEachWithEntity<Projectile>
    {
        [NativeDisableParallelForRestriction] public BufferFromEntity<ProjectileBuffer> projectileBuffer;

        public void Execute(Entity entity, int index, ref Projectile p)
        {
            if (!p.placedInBuffer)
            {
                var buff = projectileBuffer[p.dst]; //get the projectile buffer of the unit entity
                buff.Add(entity);
                p.placedInBuffer = true;
            }
        }
    }

This works fine for the most part but I am getting frequent errors of the type:

IndexOutOfRangeException: Index 8 is out of range in DynamicBuffer of ‘170’ Length.

IndexOutOfRangeException: Index 8 is out of range in DynamicBuffer of ‘170’ Length.
Unity.Entities.DynamicBuffer1[T].CheckBounds (System.Int32 index) (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/Iterators/DynamicBuffer.cs:84) Unity.Entities.DynamicBuffer1[T].set_Item (System.Int32 index, T value) (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/Iterators/DynamicBuffer.cs:126)
Unity.Entities.DynamicBuffer1[T].Add (T elem) (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/Iterators/DynamicBuffer.cs:199) ShootingSystem+AssignProjectileToBuffer.Execute (Unity.Entities.Entity entity, System.Int32 index, Projectile& p) (at Assets/Scripts/ECS/Systems/Units/ShootingSystem.cs:72) Unity.Entities.JobForEachExtensions+JobStruct_Process_EC2[T,T0].ExecuteChunk (Unity.Entities.JobForEachExtensions+JobStruct_Process_EC2[T,T0]& jobData, System.IntPtr bufferRangePatchData, System.Int32 begin, System.Int32 end, Unity.Entities.ArchetypeChunk* chunks, System.Int32* entityIndices) (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/IJobForEach.gen.cs:1683) Unity.Entities.JobForEachExtensions+JobStruct_Process_EC2[T,T0].Execute (Unity.Entities.JobForEachExtensions+JobStruct_Process_EC`2[T,T0]& jobData, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at Library/PackageCache/com.unity.entities@0.0.12-preview.33/Unity.Entities/IJobForEach.gen.cs:1656)

Is it saying that index number 8 of the dynamic array is out of bounds when the dynamic buffer has a length of 170? If so how?

Look at your code. What you’re doing is not safe.

What happens if you have 2 projectiles with the same destination?

You’d access the buffer from 2 different threads at the same time - this is a nono and why the safety system exists which you’ve turned off.

1 Like