How to allow native container for parallel writing after declearing it fron inside job ?

Hello,
I am creating nativelist inside job like this(using 19.1)

var p = new NativeList<int>(Allocator.Temp);

I need to write and read from list but unity throwing an error that
InvalidOperationException: The native container has been declared as [WriteOnly] in the job, but you are reading from it.
But how can I assign field initializers inside a struct ?

Show the full job

1 Like

Declaring native Containera from a job is not a good idea.

Do not allocate managed memory in jobs
Allocating managed memory in jobs is incredibly slow, and the job is not able to make use of the Unity Burst compiler to improve performance.

This isn’t managed memory.

Quicktest using 2019.1.0f2, this works even with burst:

using System.Linq;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using UnityEngine;

class AllocTest : JobComponentSystem
{
    [BurstCompile]
    struct AllocJob : IJob
    {
        public NativeArray<int> result;

        public void Execute()
        {
            var p = new NativeList<int>(Allocator.Temp);
            p.Add(0);
            p.Add(1);
            p.Add(2);
            p.Add(3);
            p.Add(4);
            for (var i = 0; i < p.Length; i++)
                p[i] *= 2;
            for (var i = 0; i < p.Length; i++)
                result[i] = p[i];
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var result = new NativeArray<int>(5, Allocator.TempJob);
        var job = new AllocJob
        {
            result = result
        }.Schedule(inputDeps);
        job.Complete();
        Debug.Log(string.Join(",", result.Select(i => i.ToString())));
        result.Dispose();
        return job;
    }
}
1 Like

Hello, Thanks for the help but actually I made a small mistake in my code due to which unity was throwing an error.