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
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class DoOnMainThread : MonoBehaviour { public readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>(); public void Update() { // dispatch stuff on main thread while (ExecuteOnMainThread.Count > 0) { ExecuteOnMainThread.Dequeue().Invoke(); } } } |
2) Add your coroutine action into the queue whenever you want to call it like this:
1 2 3 | DoOnMainThread.ExecuteOnMainThread.Enqueue(() => { StartCoroutine(randomcoroutine); } ); |
Of course you can add any action to the main queue at any point and whereever you want. Enjoy (:
August 17, 2014 at 6:41 am
Glad you find it interesting :) the rss should work under: http://blog.kibotu.net/feed though
April 28, 2015 at 11:15 pm
Not sure is it thread-safe realization.
July 22, 2015 at 12:52 am
this works! THX!
August 25, 2015 at 2:47 pm
Your “- See more at: http://blog.kibotu.net/unity-2/unity-start-coroutines-main-thread-anything-else-matter#sthash.yY2vRJzd.dpuf” is really retarded when trying to paste code.
October 23, 2015 at 8:47 am
Thank you so much, you saved me a few a hours of searching a pulling my hair off ;-)
April 2, 2016 at 2:58 am
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
July 17, 2017 at 11:32 pm
This is not thread-safe. You must use lock() on the Action queue when En/Dequeueing.