Optimization — Caching WaitForSeconds In Unity Coroutines

Alwin Kuruvilla
1 min readFeb 11, 2022

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:

  1. Create a private WaitForSeconds variable as seen outlined in red.
  2. Initialize the variable in a method as seen outlined in blue(Preferably the Start() or Awake() function.)
  3. Yield return the newly created variable.

AND THAT’S IT!

Happy Coding!

--

--