11 Nov 2015

Access Unity API from a thread – Multi threading

As we all know, Unity is not thread safe. Even though you can create and maintain your own threads, every call to Unity API, must be on the main thread. You can either return data from thread or design a workaround using Coroutines. There are plugins to manage multi threading in Unity. Almost all of them are paid – Unity ThreadHelper, LOOM etc.

UPDATE – UnityThreadHelper Tutorial

The limitation of Editor Thread Dispatcher, is that it works only in Unity Editor. If you create a standalone build, it won’t work. Thankfully, UnityThreadHelper has a free version. You can get it from here.

Setting up the asset

Unzip and move the script folder to your Unity project. Since these are classes, you don’t have to import anything. You can dispatch functions into Unity main thread using –


UnityThreadHelper.Dispatcher.Dispatch(() =>function_name(param1, param2 ... paramN));

This works in standalone builds also. You can find the documentation for UnityThreadHelper here.If you want to check things out just in the Editor, read the following tutorial.

Editor Thread Dispatcher Tutorial

This is a tutorial on how to access Unity API from a thread using the free plugin – Editor Thread Dispatcher.

Setting up the asset

Download the asset from Unity Asset store and import the package by going to Assets>Import package. Select all the files in the import browser and click import.

How to use Dispatcher.cs

To initiate a thread, use


new Thread(function_name).Start();

Inside the thread, when you want to call Unity API use the Dispatcher class.


Dispatcher.Dispatch((System.Action<paramter_for_the_function>)function_name, function_parameter);

This will dispatch the function to the main thread. The plugin works only in Unity Editor.
Happy coding!