Optimization principal 4: Call methods as few times as possible. While it is very simple to put logic into Update()
and have it regularly executed each frame, we can improve the game performance by executing logic as occasionally as possible. So, if we can get away with only checking for some situations every five 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 only be executed every five seconds. This could be useful for non-player characters to decide whether they should randomly "wake up", or perhaps choose a new location to start moving towards.