Using coroutines to split up complex work
So you've got a function that taxes the CPU too much. What do you do now? Sometimes you can pare down your experience to create a little more breathing room for your CPU, but obviously it's preferable to figure out a way to split all of the workup so that it can be done in a more conservative manner, even if it takes slightly longer.
This is where Unity's coroutine system comes in. Coroutines are functions that can run for a while, yield to other functions, and then pick up right where they left off. In this section, we'll modify the GenerateRandomNumbers
function to be a coroutine so that it can generate one million random numbers without ever blocking the other functions the CPU is responsible for.
There are a few caveats to coroutine functions as well, which we'll cover in this section. One that will immediately impact our function is the required return type; all coroutines must return an IEnumerator
object, so we'll have to change GenerateRandomNumbers...