I’m using the jobs system to generate terrain data and run marching cubes. Everything is running fine until I suddenly get this error after the game is running for a minute A Native Collection has not been disposed, resulting in a memory leak.
The error is generated from the densityMap allocated here:
public TerrainChunk (int size, float voxelSize, MeshObject meshObject) {
this.meshObject = meshObject;
this.voxelSize = voxelSize;
this.size = size;
densityMap = new NativeArray<float>((size + 1).Pow(3), Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
vertexCounter = new Counter(Allocator.Persistent);
}
I make sure to Dispose the native collection when I am done with it (when the game quits)
public void Dispose () {
CompleteRunningJobs();
densityMap.Dispose();
}
The system still gives me an error a little while after a job using the collection is completed. I understand that I didn’t dispose of the collection after the job completed, but that is kind of the point. It should stay alive as long as the terrain chunk is alive. That way I can reuse the collection when the user modifies the terrain.
The full source code is available here GitHub - KuroiRoy/Fast-Unity-Marching-Cubes: Marching Cubes with destructible terrain made in Unity utilizing latest Unity features, like collider baking on separate threads and setting raw mesh buffers.
Is there a way to avoid this error? Do I have to keep my data in a managed array until I run a new job on it?
Is it because I’m not keeping my native collection in a monobehaviour?