NativeArray.IsDisposed (Closed)

I find myself in a situation where I need to dispose data that might have already been disposed and need to manually track if I disposed already.

Would be much easier and save some mess if I was able to check something like:

myNativeArray.IsDisposed

or perhaps more accurate

if(!myNativeArray.IsDeAllocated)

https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.IsCreated.html
https://github.com/Unity-Technologies/UnityCsReference/blob/85c787eca6a94c9bc5cdc0ac8b72144fe03054bc/Runtime/Export/NativeArray/NativeArray.cs#LL164C21-L164C27

IsCreated isn’t enough. My scenario is sort of like:

if(myNativeArray.IsCreated)
myNativeArray.Dispose(); << disposed happily

if(myNativeArray.IsCreated)
myNativeArray.Dispose();<<error here, the array is created but already disposed

The buffer is cleared on disposal. IsCreated will be false.

1 Like

Sounds like I need to submit a bug report instead then :confused:

I see IsCreated as being true in this scenario (well a more complex one than this, the data is stored in a dictionary of NativeArray so it could be something to do with that)

NativeArray is a value type. Tracking disposal in any value type across copied instances of it will never be an option.

Its not a copied instance, I store the reference of it in a dictionary.

So two pieces of logic in two different parts of the code can both dispose this data since they both have a reference to it in different ways.

A more complete picture:
Building a minecraft like game
Chunks hold onto topBlockData
The map also references this data
As chunks unload, they create new topBlockData. The map holds onto the old one
The game quits. I check all chunks and dispose their topBlockData to catch situations where it created the array but hadn’t finished generating so it never registered with the map
The map also disposes all its data since it now has references to topBlockData for chunks that had to unload after exploring a long way

They both reference the same data so that when players change the world, topBlockData is automatically updated in the map to save having to change data in two places

The “reference” in the dictionary is a copy of the struct. The NativeArray is a value type. It contains a field identifying the start of the buffer it is meant to represent. Disposing via one copy of a NativeArray struct will not affect the fields of other occurrences of the NativeArray that were created and stored to different class fields, or local variables at other points in time. The NativeArray copy in the dictionary will be pointing to stale memory after disposal until reassigned with a blank NativeArray that does not point to any memory.

Ahh duh I’m with you now! Thanks for that :slight_smile:

The Dispose method in the Native collections does not adhere to .NET design specifications.

According to the third paragraph of this document:

1 Like