When enemy movement runs on Unity’s main thread, it leaves other CPU cores unused. Jobs can split array-based work across worker threads, building on data-oriented design to make parallel processing more manageable. section 12.2 section 12.0
Listing 12.8 Parallel enemy movement using IJobParallelFor
[BurstCompile] #A
struct MoveEnemiesJob : IJobParallelFor #B
{
[ReadOnly] public NativeArray<int> AliveEnemyIndices; #C
[ReadOnly] public NativeArray<int> EnemyType;
[ReadOnly] public NativeArray<float> EnemyVelocity;
[NativeDisableParallelForRestriction] #D
public NativeArray<float2> EnemyPosition;
public float DT;
public void Execute(int i) #E
{
int enemyIndex = AliveEnemyIndices[i];
float2 pos = EnemyPosition[enemyIndex];
float2 dir = -math.normalizesafe(pos);
float speed = EnemyVelocity[EnemyType[enemyIndex]];
EnemyPosition[enemyIndex] = pos + dir * speed * DT;
}
}The parallel enemy-movement job shows how to define per-enemy work with IJobParallelFor, mark shared inputs read-only, and write updated positions. section 12.2
Keep these practical constraints in mind:
- Schedule work and wait for it to complete before continuing; both steps add overhead. section 12.2
- Parallel writes must target distinct locations; disabling Unity’s parallel-for restriction requires ensuring that indices do not overlap. section 12.2
- Use Jobs when the workload justifies scheduling costs, and add parallel GameObject transform updates only when they are a bottleneck. section 12.5
