首页 > 解决方案 > How do you reference an array item within nativeArrray in ECS

问题描述

I'm trying to do the following:

private void AssignPlayer()
{
    EntityQuery playerQuery = GetEntityQuery(ComponentType.ReadOnly<PlayerTag>());
    Entity playerEntity = playerQuery.ToEntityArray(Allocator.Temp);

    Entities.
        WithAll<ChaserTag>().
        ForEach((ref TargetData targetData) =>
        {
            if (playerEntity != Entity.Null)
            {
                targetData.targetEntity = playerEntity;
            }

        }).Schedule();
}

But the line that assigns targetData.targetEntity = playerEntity; throws the error:

Cannot implicitly convert type 'Unity.Collections.NativeArray<Unity.Entities.Entity>' to 'Unity.Entities.Entity'

标签: unity3dunity-dotsunity-ecs

解决方案


if( players.Length!=0 )
{
    NativeArray<Entity> players = playerQuery.ToEntityArray( Allocator.TempJob );
    Entities.WithName("targetData_update_job")
        .WithReadOnly( players ).WithDeallocateOnJobCompletion( players )
        .WithAll<ChaserTag>()
        .ForEach( ( ref TargetData targetData ) =>
        {
            targetData.targetEntity = players[0];
        }
        ).ScheduleParallel();
}
else Debug.LogWarning($"{nameof(AssignPlayer)}(): no players tho");

推荐阅读