I've made many entity jobs before but now I'm trying to jobify simple math using IJobParallelFor, and getting the result to put into an entity job. I've made every parameter in the job read only except for one, which is the array the job will be writing to, however unity thinks that the value is read only for some reason... what am I doing wrong?
public struct TowerAimJob : IJobParallelFor
{
public NativeArray<TowerTarget> towerTargets;
[ReadOnly] public NativeArray<Enemy> enemies;
[ReadOnly] public NativeArray<LocalTransform> enemyTransform;
[ReadOnly] public NativeArray<Tower> towers;
[ReadOnly] public int enemyCount;
public readonly void Execute(int towerIndex)
{
//Calculate based on readonly arrays
//this line gives error
towerTargets[towerIndex] = new TowerTarget { /* values */ };
}
}
If it matters, here is how I am feeding values to create the parallel job:
//Context: This method gets entity queries of both towers and enemies. After converting the queries into arrays, for each tower placed in the game I calculate all enemies in range and the choose the one closest to the enemies target. Each job created will be for calculating the target of one tower each.
private NativeArray<TowerTarget> GetTowerTargets(EntityQuery towerQuery, int towerCount, EntityQuery enemyQuery, int enemyCount)
{
NativeArray<Enemy> enemies = enemyQuery.ToComponentDataArray<Enemy>(Allocator.TempJob);
NativeArray<LocalTransform> enemyTransform = enemyQuery.ToComponentDataArray<LocalTransform>(Allocator.TempJob);
NativeArray<Tower> towers = towerQuery.ToComponentDataArray<Tower>(Allocator.TempJob);
NativeArray<TowerTarget> towerTargets = new(towerCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
TowerAimJob towerAimJob = new()
{
towerTargets = towerTargets,
//some other readonly values here
};
JobHandle jobHandle = towerAimJob.Schedule(towerCount, 1);
jobHandle.Complete();
return towerTargets;
}
What am I doing wrong? Or am I using the jobs system in the wrong way?