EntityQuery.ToComponentDataArray what's the alternative?

Hey! I’m trying to make a system for enemy chasing the closest player. For this I need a NativeArray with the Player’s LocalPosition. At first I used ToComponentDataArray to get the array. It was too slow so now I found a solution to fill the NativeArray via Entities.Foreach(). But this doesn’t help either and I get a lot of delay. 100 entity on scene.

Code:

 public partial class EnemyFollowPlayerSystem : SystemBase
{
     EntityQuery playerQuery;
     protected override void OnCreate()
     {
         playerQuery = GetEntityQuery(typeof(PlayerTagComponent), ComponentType.ReadOnly<LocalTransform>());
         RequireForUpdate(playerQuery);
     }

     protected override void OnUpdate()
     {
         int arrayLeght = playerQuery.CalculateEntityCount();
         NativeArray<LocalTransform> playersTransforms = new NativeArray<LocalTransform>(arrayLeght, Allocator.TempJob);

         int entityInQueryIndex = 0;

         Entities.WithAll<PlayerTagComponent>().ForEach((ref LocalTransform localTransform) =>
         {
             playersTransforms[entityInQueryIndex] = localTransform;
             entityInQueryIndex++;
         }).Run();

         EnemyFollowPlayerJob enemyFollowPlayerJob = new EnemyFollowPlayerJob();
         enemyFollowPlayerJob.playerTransforms = playersTransforms;
         enemyFollowPlayerJob.Run();
     }
}

public partial struct EnemyFollowPlayerJob : IJobEntity
{
     [ReadOnly]
     public NativeArray<LocalTransform> playerTransforms;

     public void Execute(in EnemyTagComponent enemyTag, ref LocalTransform transform, ref AgentBody agent)
     {
         float3 nearestPlayerPosition = new float3(0, 0, 0);
         float minDistance = 0;

         foreach (LocalTransform playerTrs in playerTransforms)
         {
             float distanceToPlayer = math.distance(transform.Position, playerTrs.Position);
             if (distanceToPlayer < minDistance || minDistance == 0)
             {
                 nearestPlayerPosition = playerTrs.Position;
                 minDistance = distanceToPlayer;
             }
         }

         agent.SetDestination(nearestPlayerPosition);
     }
}

What did I miss?

The issue is that you are trying to run things on the main thread, and that requires waiting for jobs to complete. You can fix this by making your jobs scheduled instead.

It work! Thanks!