ComponentDataArray -> NativeArray?

How would I pass values in a ComponentDataArray into a NativeArray for use in a job? My current approach does not change the Vector3 in the component that it should - I think this problem happens around lines 32-37.
I believe this is because it is not a reference, but I am not sure how to go about fixing this.

using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using UnityEngine;

public class CubeMoveSystem : ComponentSystem
{
    //Getting and injecting cubes
    public struct Cubes
    {
        public int Length;
        public ComponentArray<Transform> transforms;
        public ComponentDataArray<Velocity> velocities;
    }
    [Inject] Cubes cubes;

    //The actual job which increases the velocity by mod
    struct UpdateVelocitiesJob : IJobParallelFor
    {
        public NativeArray<Vector3> velocities;
        public Vector3 mod;

        public void Execute(int i)
        {
            velocities[i] = velocities[i] + mod;
        }
    }

    protected override void OnUpdate()
    {
        //Filling the NativeArray with all the velocities from the ComponentDataArray
        NativeArray<Vector3> velocities = new NativeArray<Vector3>(cubes.Length, Allocator.TempJob);

        for (int i = 0; i < cubes.Length; i++)
        {
            velocities[i] = cubes.velocities[i].value;
        }

        //Creating the job
        UpdateVelocitiesJob updateVelocitiesJob = new UpdateVelocitiesJob()
        {
            velocities = velocities,
            mod = Velocity.mod
        };

        //Doing the job
        JobHandle updateVelocitiesJobHandle = updateVelocitiesJob.Schedule(cubes.Length, 1);
        updateVelocitiesJobHandle.Complete();

        //Disposing the array
        velocities.Dispose();
    }
}
using Unity.Entities;
using UnityEngine;

[System.Serializable]
public struct Velocity : IComponentData
{
    public Vector3 value;

    public static Vector3 mod = new Vector3(.1f, .1f, .1f);
}

public class VelocityComponent : ComponentDataWrapper<Velocity> { }

Why you simply not use ComponentDataArray in job?

struct UpdateVelocitiesJob : IJobParallelFor
    {
        public ComponentDataArray<Velocity> velocities;
        [ReadOnly] public Vector3 mod;

        public void Execute(int i)
        {
            var _tmp = velocities[i];
            _tmp .Value = velocities[i].Value + mod;
            velocities[i] = _tmp;
        }
    }
1 Like

…oh, you can do that? Thought that only NativeArrays could be passed between jobs, whoops.

Thank you!

You can pass all blittable values in to job

2 Likes