Unity C# Job System and Coroutines
I’ve been learning to use Unity for game development through a course at MSU. Once of the things I’ve struggled with is how to cleanly handle waiting for a job to execute off thread so expensive operations can easily be farmed off to be processed outside of the main thread. Unity can still be frustrating single-threaded at times, so having the ability to easily shift work into threads when it makes sense can make all the difference.
This is a pattern I wasn't able to find even following hours of searching, so I'm not sure if this is unknown, or simply unknown to me. Either way, here's the gist of it so you can leverage it in your own games.
First, let’s start with a basic job in Unity, which might look something like this:
using Unity.Jobs;
public struct MyJob : IJob
{
public void Execute()
{
// Do something cheap, like compute the number of atoms in the universe
}
}
Now that you've got your job, you can go ahead and call it from your Start()
or Update()
function using a coroutine!
using UnityEngine;
using System.Collections;
public struct MyComponent : MonoBehaviour
{
void Start()
{
StartCoroutine(ExpensiveCalculation());
}
IEnumerator ExpensiveCalculation()
{
var job = new MyJob();
var handle = job.Schedule();
// This is the magic
while (!handle.IsCompleted)
yield return null;
handle.Complete();
// Do something with your job results
}
}
Since Coroutines always run on the main thread, this allows you to do anything you might need to do, including manipulating physics, with the result of the job.
My previous approaches to this problem involved caching jobs and handles in class fields, which becomes nasty to use. This, by contrast, seems much simpler and should be relatively straight forward to implement wherever you need it.