1
\$\begingroup\$

I am trying to find out the distance between game objects and the player position using Job System, But I am getting an error of unsafe pointer race condition. Can anyone tell me how to access transform in job system? to measure distance. Following is the code.

struct PositionUpdateJob : IJobParallelForTransform

{

    public TransformAccessArray Object;

    public float DIst;


    public void Execute(int i, TransformAccess transform)

    {

         DIst = (transform.position- Object[0].position ).sqrMagnitude;
        if (DIst < 20)
        {
           // Do Something
        }
    }

}

This is the Main script which measures gameObject position against its children

public Transform Player;
public List<Transform> ChildList = new List<Transform>();    
public TransformAccessArray Transformz;
public float Dist;
PositionUpdateJob m_Job;
JobHandle m_PositionJobHandle;  
public TransformAccessArray Mey;
void Start ()
{
    Transformz = new TransformAccessArray(0, -1);
    Mey = new TransformAccessArray(0,-1);
    Mey.Add(transform);
    GetChildRecursive(gameObject);
    }
private void GetChildRecursive(GameObject obj)
{
 //To Get All childrens for transform access array
}
void Update()
{
    m_PositionJobHandle.Complete();
    m_Job = new PositionUpdateJob()
    {
        DIst = Dist,
        Object = Mey
};
    m_Job.Schedule(Transformz);
  }
private void LateUpdate()
{
    m_PositionJobHandle.Complete();
    Transformz.Dispose();
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Have you considered working on an array of positions, instead of an array of transforms? \$\endgroup\$ – DMGregory Nov 15 '18 at 11:14
1
\$\begingroup\$

So after getting some help from the unity forum I fixed the problem. I am posting code below hope it will help someone:)

struct PositionUpdateJob : IJobParallelForTransform

{
    public NativeArray<float> _distances;
    public Vector3 _playerPosition;

    public void Execute(int i, TransformAccess transform)
    {
        _distances[i] = Vector3.Distance(_playerPosition, transform.position);
    }
}


PositionUpdateJob job = new TransformDistanceCheckJob()
    {
        _distances = distances,
        _playerPosition = Player.position,
    };
    JobHandle jobHandle = job.Schedule(Transformz);
    jobHandle.Complete();
    for (int i = 0; i < distances.Length; i++)
    {
        UnityEngine.Debug.Log("distance for for index " + i + ": " + distances [i]);
    }

Ps: Performance is great on 5000 children with burst compiler it takes around 2ms where without job system it was 8ms.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.