Spreading long computations over several frames with coroutines
Optimization principal 3: Call methods as few times as possible.
Coroutines allow us to write asynchronous code—we can ask a method to go off and calculate something, but the rest of the game can keep on running without having to wait for that calculation to end. Or, we can call a coroutine method for each frame from Update()
and organize the method to complete part of a complex calculation each time it is called.
Note that coroutines are not threads, but they are very handy in that each can progress each frame further. It also allows us to write code that does not have to wait for certain methods to complete before another can begin.
When games start requiring complex computations, such as for artificial intelligence reasoning, it may not be possible to maintain acceptable game performance when trying to complete all calculations in a single frame—this is where coroutines can be an excellent solution.
This recipe...