Unity ECS:将组件数组插入IJobProcessComponentData

时间:2018-06-14 15:46:11

标签: c# entity-framework unity3d

[固定在臀部] 我正在用鸟类进行小型模拟,鸟类必须根据其他鸟类的位置做不同的事情。 所以我想将一个位置数组(其他鸟类所在的位置)插入到IJobProcessComponentData中,如下面的代码所示。但是,当代码运行时,我得到一个错误:

  

InvalidOperationException:NativeContainer   CohesionJob.Data.Neighbours.Birds已被解除分配。所有容器   在安排工作时必须有效。

using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Transforms2D;
using UnityEngine;
using Unity.Burst;

public class CohesionSystem : JobComponentSystem
{
    public struct BirdsData
    {
        [ReadOnly]
        public ComponentDataArray<Bird> Birds;
        [ReadOnly]
        public ComponentDataArray<Position> Pos;
        public int Length;
    }

 [Inject] BirdsData OtherBirds;

 public struct CohesionJob : IJobProcessComponentData<Bird, Position, Cohesion>
 {
    public BirdsData Neighbours;

    public void Execute([ReadOnly] ref Bird bird, ref Position position, ref Cohesion cohesion)
    {
        float3 center = new float3();
        int amount = 0;

        for (int i = 0; i < Neighbours.Length; i++)
        {
            if(Vector3.Distance(Neighbours.Pos[i].Value, position.Value) <= cohesion.Radius)
            {
                center += Neighbours.Pos[i].Value;
                amount++;
            }
        }

        center /= amount;

        center = position.Value - center;

        cohesion.Value = center;
    }
 }

 protected override JobHandle OnUpdate(JobHandle inputDeps)
 {
    var job = new CohesionJob
    {
        Neighbours = OtherBirds
    };
    return job.Schedule(this, 64, inputDeps);
 }
}

所以为了解决这个问题,我必须复制“OtherBirds.Pos”数组,这样做的代码如下所示:

protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var job = new CohesionJob
        {
            Neighbours = new NativeArray<Position>(OtherBirds.Pos.GetChunkArray(0, OtherBirds.Pos.Length), Allocator.Temp)
        };
        return job.Schedule(this, 64, inputDeps);
    }

0 个答案:

没有答案