Spreading long computations over several frames with coroutines

Optimization principal 3: Call methods as few times as possible.

Coroutines allow us to write asynchronous code—we can ask a method to go off and calculate something, but the rest of the game can keep on running without having to wait for that calculation to end. Or, we can call a coroutine method for each frame from Update() and organize the method to complete part of a complex calculation each time it is called.

Note that coroutines are not threads, but they are very handy in that each can progress each frame further. It also allows us to write code that does not have to wait for certain methods to complete before another can begin.

When games start requiring complex computations, ...

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.