Coroutines with Unity!

Coroutines are used when you need to run some code that has a pause aka yield before continuing or you could use it for a sequence of events with multiple yields. For example, in an infinite loop like while(true) you need to have a yield in it or it will crash the program.
According to Unity’s Manual a Coroutine is essentially a function/method declared with a return type of IEnumerator and with a yield return statement included somewhere in the body.

There are a number of different yield return statements you can use but I’ve found yield return null and yield return new WaitForSeconds to be the most common.
yield return null will pause and resume on the next frame.
yield return new WaitForSeconds allows you to implement a time delay, it suspends the coroutine execution for the given amount of seconds using scaled time which is the time given divided by Time.timeScale
If you want to use unscaled time then you should use WaitForSecondsRealTime.
To start a coroutine you need to use StartCoroutine
You can call it directly like this… StartCoroutine(SpawnRoutine());
If you want to be able to use StopCoroutine then you need to store a reference to the coroutine and use that when starting it or use a string when you start it, when you stop you have to use the same way that you started it.
In my GIF at the top of this page I am using a Coroutine in my SpawnManager to spawn an enemy every 5 seconds.

I’m also using a coroutine to make the enemy cube disable it’s collider after being hit by a laser, activate smoke particles, wait a second, explode, wait half a second, disable mesh renderer and wait 10 seconds before destroying it all so the smoke has time to disappear gradually.

Best practice for performant code is to cache the WaitForSeconds so that anew one isn’t created for each event. I also have the time serialized so it can be edited in the inspector.

