Optimization — Caching WaitForSeconds In Unity Coroutines
Unity coroutines are a great way to spread tasks across several frames in your games. You can also use coroutines to incorporate a delay in executions by using yield return new WaitForSeconds();
inside the coroutine.
Using WaitForSeconds()
is great however you can increase performance by caching WaitForSeconds()
prior to starting the coroutine. Let’s take a quick look on how to do this:
Above, we have a normal coroutine called SpawnRoutine()
. It will spawn an enemy and pause execution for whatever amount of time is set for spawnDelay
(three seconds in this example.) Now let optimize the code by caching the WaitForSeconds
!
There are 3 things you’ll need to do:
- Create a
private WaitForSeconds
variable as seen outlined in red. - Initialize the variable in a method as seen outlined in blue(Preferably the
Start()
orAwake()
function.) - Yield return the newly created variable.
AND THAT’S IT!
Happy Coding!