Executing methods regularly but independent of frame rate with coroutines
Optimization principal 3: Call methods as few times as possible.
While it is very simple to put logic into Update()
and have it regularly executed for each frame, we can improve game performance by executing logic as rarely as possible. So, if we can get away with only checking for a situation every 5 seconds, then great performance savings can be made to move that logic out of Update()
.
A coroutine is a function that can suspend its execution until a yield
action has completed. One kind of yield action simply waits for a given number of seconds. In this recipe, we use coroutines and yield to show how a method can be only executed every 5 seconds; this could be useful for NPCs to decide whether they should randomly wake up or perhaps choose a new location to start moving toward.
How to do it...
To implement methods at regular intervals independent of the frame rate, follow these steps:
- Add the following C# script class...