I’m using, Unity 2018.3.3f1’s Job System and RaycastCommand. I basically modified the example that can be found in the RaycastCommand documentation. In my script NativeArrays must change size when needed.
Some context:
Initialize
var hitResults = new NativeArray<RaycastHit>(targets.Length * sources.Length, Allocator.TempJob);
var commands = new NativeArray<RaycastCommand>(targets.Length * sources.Length, Allocator.TempJob);
Create Commands
commands[j * targets.Length + i] = new RaycastCommand(
sources[i].position,
Vector3.Normalize(targets[j].position - (float3)sources[i].position),
Mathf.Infinity
);
Do Schedule Batch
// Schedule the batch of raycasts
jobHandle = RaycastCommand.ScheduleBatch(commands, hitResults, raycastingOptions.m_minCommandsPerJob, default(JobHandle));
// Wait for the batch processing job to complete
jobHandle.Complete();
And after processing results…
Deallocate
hitResults.Dispose();
commands.Dispose();
I know this full sequence should not be done in every Update (and I am changing that) but, for the sake of testing, if I do so, it works but Unity, in an inconsistent way, starts spitting these errors:
: Index 2800 is out of range of '2800' Length.
Unity.Collections.NativeArray`1[T].FailOutOfRangeError (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:207)
Unity.Collections.NativeArray`1[T].CheckElementWriteAccess (System.Int32 index) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:126)
Unity.Collections.NativeArray`1[T].set_Item (System.Int32 index, T value) (at C:/buildslave/unity/build/Runtime/Export/NativeArray/NativeArray.cs:145)
GIA.Raycasting.RaycastingEngine.RaycastCompute () (at Assets/RaycastBatchingResearch/Overshadowing/Scripts/RaycastingEngine.cs:116)
GIA.Raycasting.RaycastingEngine.Update () (at Assets/RaycastBatchingResearch/Overshadowing/Scripts/RaycastingEngine.cs:62)
Internal: JobTempAlloc has allocations that are more than 4 frames old - this is not allowed and likely a leak
To Debug, enable the define: TLA_DEBUG_STACK_LEAK in ThreadsafeLinearAllocator.cpp. This will output the callstacks of the leaked allocations
Where 2800 is the total new size of the commands NativeArray.
This error seems less likely if I change size and reallocate sporadically.
The weird thing is that if you take the example in the RaycastCommand docs and execute it every update it works and it resizes the arrays correctly. It seems to depend on how much stuff is done in the middle, I guess the jobs go out of sync with the Unity cycle?
I do not understand exactly what’s going wrong. Is there a better way to resize NativeArrays (other than reinitialize them with “new NativeArray”)?
How do I stop this from happening and let the arrays change whenever I please (even in every update perhaps)?
Thanks in advance.