Coroutines with Unity

Computers process information at MILLIONS of instructions per second (MIPS). A 2018 Intel Core i7 is rated at 221,720 MIPS! So how do we get the computer to slow down and wait for our pathetic human brains? The answer is coroutines.

When the edibles kick-in.

We’ve given Ethan the special ability to stealth. But he can’t do it himself; to access this particular mutant X-gene, he needs to touch a golden sphere power-up. (Question not the “logic” of video games.) Here is the power-up’s code:

When Ethan touches the power-up, it calls the ActivateStealth method Ethan’s Stealth component and tells it how long to remain “stealthed.” In this case, two seconds.

“That’s not enough stealth time, brosphine!

Ethan’s ActivateStealth method in turns calls the GoStealth coroutine, and passes-in the duration from the power-up. The highlighted line below tells the computer to wait until the duration has passed before reverting Ethan back to his normal form. The cool thing about coroutines is the script can do other things while the coroutine runs!

Now, the savvy among you may be saying, “bro, why didn’t we just call the GoStealth subroutine from the power-up instead of calling another method to call it?” Well, I tried that bro, and Ethan stayed “stealthed” permanently. Since the power-up destroys itself immediately after calling the subroutine, the yield return never gets to report back to the thing that called it. So not even a Debug.Log(“Duration over.”); placed after the yield return executed. Live and learn!

An independent Unity Developer.