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 ...

Get Unity 5.x Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.