While working on our API.AI Unity SDK I faced with task to make HTTP requests in the background thread. In the Unity there is c# Thread
class, which runs particular code in background. But you can't interact with your game objects from background thread. So, I need some tool to execute code from our background thread in the Unity Main Thread. Another platforms solve this problem with different mechanisms, like Dispatcher. But in Unity there is no similar class for this. Quick search give me some tricks allowing to execute code in the main thread, and I describe the simpliest one here.
The main idea of the method is to create Queue
of actions, and execute these actions in the Update
method of MonoBehaviour
class.
First, suppose that we have some MonoBehaviour
class.
public class TestModule : MonoBehaviour
{
}
We should add actions queue field to it
private readonly Queue<Action> ExecuteOnMainThread = new Queue<Action>();
Let's add code for actions execution in the Update
method (create it if not exists)
// Update is called once per frame
void Update()
{
// dispatch stuff on main thread
while (ExecuteOnMainThread.Count > 0)
{
ExecuteOnMainThread.Dequeue().Invoke();
}
}
Near we will add method to add items to the queue
private void RunInMainThread(Action action)
{
ExecuteOnMainThread.Enqueue(action);
}
Now, we ready to interact with Unity from background thread:
private void SomeBackgroundMethod()
{
var result = makeHttpRequest();
// process result in the main thread
RunInMainThread(() => {
answerTextField.text = result.Message;
});
}
The usage of the method you can see here.
Possible improvements:
Instead of simple Queue
it is better to use ConcurrentQueue
. But in Unity there is no such class. So, we need use own implementation like here.