#Default value for native container (no memory allocation)

1 messages · Page 1 of 1 (latest)

onyx oyster
#

Is this possible to use some sort of default value for native containers? For normal arrays I would use null but since they are value types it does not work 😦
Otherwise I don't know how to initialize my jobs output NativeArrays when I don't know their size when constructing the job (the size is calculated inside the job).

#

The only thing I can think of would be :
output = new NativeArray<int>(0, Allocator.TempJob);
output.Dispose()
But that looks horrible 😅

That does not even work 😫

#

Or should I make another job to calculate the size and run that job first?

sterile hearth
#

We use this property to verify if the native container is initialized or not

onyx oyster
#

Thank you but my question is how can I create a not (yet) initialized container?

#

Because when constructing a struct, all variables have to have a value if I am correct

onyx oyster
#

With which allocator?

sterile hearth
#

Btw, this code will give you a native array of 10 elements, and each element has a default value of 0

var arr = new NativeArray<int>(10, Allocator.Temp);
onyx oyster
sterile hearth
#
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
    var arr = new NativeArray<int>(10, Allocator.TempJob);
    var job = new MyJob { arr = arr };
    var dependency = job.Schedule(state.Dependency);
    arr.Dispose(dependency);

    state.Dependency = dependency;
}

[BurstCompile]
private partial struct MyJob : IJob
{
    public NativeArray<int> arr;

    public void Execute()
    {
    }
}
#

I've just double-checked it, you can create NativeArray with NativeArrayOptions.UninitializedMemory parameter. You don't have to use CollectionHelper.

onyx oyster
#

Alright I will try this, thank you!

sterile hearth
#

I use CollectionHelper when I want to use the state.WorldUpdateAllocator. For which I don't have to worry about disposing the array.

#
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
    var arr = CollectionHelper.CreateNativeArray<int>(10, state.WorldUpdateAllocator);
    var job = new MyJob { arr = arr };
    state.Dependency = job.Schedule(state.Dependency);
}
onyx oyster
#

Yes it worked thank you! 🙂

verbal plover
#

or right

#

already answered