Wednesday, August 29, 2012

Really Really Easy Multithreading in Unity3D.

When you start working with threads in your Unity3D project, you will discover that many things need to be done in the main loop. For example, if you try and do a Physics.Raycast call from a thread, you'll come across this error.

INTERNAL_CALL_Internal_RaycastTest  can only be called from the main thread.

This can be really frustrating, so, what to do? We need some Magic Threads!

The below example shows how the latest version of UnityExtender allows you to make a coroutine jump back and forth between a background thread and the foreground main loop. It doesn't get much easier than this, and it integrates perfectly with Unity coroutines. This new version of UnityExtender should be available in a few days.

    void Start () {
        MagicThread.Start(ThisIsAMagicalThread());
    }
 
    IEnumerator ThisIsAMagicalThread() {

        Debug.Log("I am running in the background.");
        //This will raise an error
        Physics.Raycast(new Ray(Vector3.zero, Vector3.forward));

        yield return new ForegroundTask();
 
        Debug.Log("I am now running in the Unity main loop.");
        //This will work!
        Physics.Raycast(new Ray(Vector3.zero, Vector3.forward));
  
        yield return new WaitForSeconds(2);

        Debug.Log("About to re-enter the background...");
        yield return new BackgroundTask();
        Debug.Log("I am running in the background again.");

    }

4 comments:

Anonymous said...

I wish I was you, Simon.

Simon Wittber said...

You can be. Just drink a bit too much beer, then open a code editor and you're half way there.

Unknown said...

Awesome work Simon. Can't wait to try it out :-)

Unknown said...

I have a bike game receives control signals from outside through the COM2 port, but I'm having a problem in handling overlapping causes up to receive the control signal very slowly.
please guide me how to handle multi-threaded to receive data from external device to control my bike.
Thanks

Popular Posts