Why does this happen? I expected the array to just copy the values over, but the array is now the same as the other array and it’s really difficult to work with because I don’t know whats going on.
Why does setting a NativeArray equal to another NativeArray point to the other array instead of copy
NativeArray is a struct that contains a pointer (essentially an int number) to a native memory location.
If you pass that array to a method or assign it to another variable, the struct itself is copied including the pointer. But since the pointer value in the copy remains the same both arrays still point to the same memory location.
This is actually a great thing! Otherwise there would be way too many memory copies happening which would be a drag on performance.
If you want a deep copy, you can use NativeArray.Copy(…) static method.
So should I think of NativeArrays as references then, at least in terms of how I should work with them?
Basically yes.
More correctly they’re value types with reference-type storage.
You’ll get used to it.
The sweet thing is that you can pass native collections around via method calls and it still uses the same memory, like when you assign a native container to a job and after the job is done, you do not need to re-assign the job’s container or even copy it, you keep using the one that you had on the main thread where you scheduled the job.
I have a question regarding this…
So if I have two NativeArrays pointing to the same memory allocation, do I have to dispose them both?
For example if i have a NativeArray on the main thread and I pass that array into a job where it’s decorated with the “DeallocateOnJobCompletion” attribute, do i still have to wait for the job to complete and dispose of the NativeArray on the main thread?
Nope. You should only ever dispose of a memory location once.