I have a class with a nested struct, this struct has a NativeArray. Everything works fine when I work with the original instance.
But as soon as I make a copy via copy constructor or Clone() I get the “A Native Collection has not been disposed, resulting in a memory leak.” error messages in the console even though, when stepping through, the collection is marked as “IsCreated = false” respectively it shows an IDisposedException in the debugger.
Unless I’m doing something illegal with the array to begin with this seems a bug in Collections 1.4.0. I hope this isn’t just because I’m not using the “recommended” version (1.2.4). Unity version is 2022.1.14f1.
Here’s the minimal test case I made:
public class TestNotDisposed
{
private NestedStruct _nested = new(Allocator.Persistent);
public TestNotDisposed() {}
public TestNotDisposed(TestNotDisposed other) => _nested = new NestedStruct(other._nested);
public void Dispose() => _nested.Dispose();
private struct NestedStruct
{
private NativeArray<int> _values;
public NestedStruct(Allocator allocator) => _values = new NativeArray<int>(4, allocator);
public NestedStruct(NestedStruct other)
: this(Allocator.Persistent) => _values.CopyFrom(other._values);
public void Dispose() => _values.Dispose();
}
}
To raise the issue just run this code anywhere, ie in a test case:
var test = new TestNotDisposed();
var copy1 = new TestNotDisposed(test);
copy1.Dispose();
test.Dispose();
I tried disabling Burst but that had no effect.
It works fine if I use Allocator.Temp but TempJob and Persistent raise this issue.