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 (: