Optimizing Coroutines in Unity

Esteban Ibarra
Nerd For Tech
Published in
Oct 31, 2021

--

Coroutines are extremely useful for any time specific function, however when one uses the yield return new function, that uses a lot of garbage allocation resources as every time the new keyword is used, Unity has to build that new thing on the spot.

This is where caching WaitForSeconds comes in. Think of Caching the WaitForSeconds as a Hot-N-Ready WaitForSeconds routine just waiting for anyone to pick it up and use it!

Since the WaitForSeconds is already built and available, when the coroutine is run, Unity doesn’t have to go through any more extra steps and potentially slow your game down!

The key takeaway here is an important concept in optimizing code is caching your data! Hope it helps!

--

--