Or is there any other way to create empty NativeArray without memory allocation?
Like this?
Not quite. NativeArrayOptions.UninitializedMemory doesn’t avoid the allocation. It just means it doesn’t clear the memory[0], which means the contents of your new array are undefined.
NativeArray is a struct, so if you want a non-allocated one, you can just use default. For example:
NativeArray<float> foo = default;
You can see the array is not created using foo.IsCreated.
This array isn’t valid in any way, though. You can’t read from it, write to it, or construct it later. It’s just an empty struct. If you try and pass it to a job Unity will throw an error as all native collections passed to jobs need to have been created.
What are you trying to achieve with this?
[0] More correctly it doesn’t initialize the memory. But the most visible result of this is that the contents are undefined
Also have you tried experimenting with Allocator.None?
Can’t you just use empty array in constructor ?
@
It leads to the exception
ArgumentException: Allocator must be Temp, TempJob or Persistent
var test = new NativeArray(Array.Empty(), Allocator.TempJob);
Empty array works fine, this may be a solution
My goal is to make default implementation of virtual method that returns empty array
protected virtual NativeArray<Entity> GetExtraEntities()
{
return NativeArray.Empty<Entity>(); //<- ?
}
protected override void OnUpdate()
{
foreach (var extraEntity in GetExtraEntities())
{
....
}
}
I’ll try
NativeArray<float> foo = default;
and post results in this thread
If it works I will be quite surprised. Since:
Mark the containers with NativeDisableContainerSafetyRestriction, and then just create them in the job not outside it. Generally used together with Temp allocations.