[Unity3D] Make a Coroutine synchronous

Unity3D coroutine synchronous

In Unity3D, Coroutine is a great tool to make parallel scripts in a safe way. However, in certain cases you may need to execute a Coroutine synchronously, and Unity does not offer any method out of the box to do so.

Here is a small code snippet you can use in C#:

If you prefer you can put the static method in a class you already have.

You can use it exactly like StartCoroutine, from anywhere in your code:

The call will block the rest of your code until the coroutine is finished.

Please let me know in comments if you find this code useful and/or if you have other Coroutine tricks!

[EDIT 28-07-2017] Add handling for InvalidCastException.

Header image based on an image by V.ivash

About Nicolas Form

I’m Nicolas Form, multi-skill programmer, aesthete and joyful French guy. On this blog I share my tips and tutorials about programming and IT in general. I am freelance, so you can also contact me about a website, an Android app or any other software you need. Check my portfolio and drop me a line!

This entry was posted in Unity3D. Bookmark the permalink.

10 Responses to "[Unity3D] Make a Coroutine synchronous"

Leave a Reply

Your email address will not be published. Required fields are marked *


*


[Unity3D] Make a Coroutine synchronous

by Nicolas Form time to read: 1 min
10