Skip to content

Reply To: MultiCore – Unity

Home Forums Developer Concurrency Kit MultiCore – Unity Reply To: MultiCore – Unity

#332
Administrator
Keymaster

You are correct, access to most Unity methods must be on the main Unity thread. This is typical of many UI frameworks as well. However, just like standard UI frameworks, it’s entirely possible to run logic off thread and at a different frequency, then callback to the main thread when the results are ready. There are different ways to set this up and it really depends on what type of logic you would like to offload or wait for (pathfinding, physics, etc.).

Ultimately it boils down to picking which scheduler you want the calls to run on. So you could do something like this:

void Start()
{
    // Grab a snapshot of the current transform and state
    var physicsState = ReadFromRigidbody();
    Task.Factory.StartNew(() => ProcessOnAnotherCore(physicsState)) // thread pool
	.ContinueWith((t) => ApplyOnUnityThread(physicsState), taskScheduler); // Unity thread
}

When you’re interacting with the Unity thread like this you will need to manage marshaling data back and forth and there are various patterns for that such as in the above example. You could have Unity push the data to another thread in Update() or you could pull the latest from another thread at whatever frequency you need it:

void ThreadPoolThread()
{
    PhysicsState physicsState;
    taskFactory.StartNew(() => CopyFromUnity(physicsState)).Wait();
    DoSomethingWithCurrentState(physicsState);
    taskFactory.StartNew(() => CopyToUnity(physicsState));
}

Longer running operations or those that run more infrequently than Unity’s Update() lend themselves better to offloading to another thread. If you’re interacting with Unity’s physics system you’ll want to take into account that the main thread can update transform data while you’re working with the copy.

I hope that explanation helps some, and please let me know if I can provide any more info.

Comments are closed.