Coroutines. Timing Your Code in Unity
Coroutines are unique functions that are provided by Unity. They allow you to control when certain lines of code execute which can be very useful if we want some actions to be delayed. They must be called with the StartCoroutine(CoroutineName()) method and they are declared like this:
Coroutines must always include the “yield return” bit, otherwise they will not work. They are very useful for when you have anything in your code where you have to wait or create some kind of delay. Here’s an example with creating a fire rate system for my character controller.
Take note that there is code above the “yield return” statement and also below it. Always remember that your code executes from top to bottom. In this case that the code above the “yield return” line will execute and then the function will wait for the number of in game seconds that fireRate is defined as before executing the last line of code. The variables canFire and fireRate are declared as globals at the top of the class so that a designer can fiddle with them if they want.
Here’s one more example using a coroutine recursively in order to infinitely spawn enemies.