Unity: Start Coroutines on main thread or anything else for that matter

In case you do some asynchronious stuff like updating a game object after a network response in unity, you might come to a point where you want to do something you which can only be done within the unity main thread. So here is a little trick which let’s a certain method be called on the next opportunity of the game loop.

1) Create a gameobject in your scene and add a this script

2) Add your coroutine action into the queue whenever you want to call it like this:

Of course you can add any action to the main queue at any point and whereever you want. Enjoy (:

Facebook comments:

comments

6 Comments

  1. Glad you find it interesting :) the rss should work under: http://blog.kibotu.net/feed though

  2. Not sure is it thread-safe realization.

  3. this works! THX!

  4. Thank you so much, you saved me a few a hours of searching a pulling my hair off ;-)

  5. Hey! Thanks for the info. Just wanted to note that your implementation is not thread-safe. I’ve created a library that does exactly this, feel free to link to it if you’d like. https://github.com/PimDeWitte/UnityMainThreadDispatcher

Leave a Reply