Journal 12 — Practice Coroutines in Unity
I first mentioned coroutines in my Journal 07 article on creating enemies. Coroutines in Unity and C# can be used for creating actions that need a specific timing, a series of steps, a series of music or visual effects, or running something that would take longer than a single frame.
Coroutines consist of a call to an IEnumerator function using the StartCoroutine command.
Coroutines in this example are used for spawning enemies at a regular interval. We add the StartCoroutine command in the Start Method, and use the Instantiate command plus a period of time to wait per each spawn in the IEnumerator function.
Without a coroutine, if you spawned enemies in the Update Method, this is what would happen:
Here’s the result with a coroutine:
Here’s another variation of the same coroutine with a random waiting period for spawning: yield return new WaitForSeconds(Random.Range(2f,5f)); This makes the enemy spawning a little more unpredictable as the game gets fleshed out.
I appreciate your time stopping by.
Thanks!