Game Development Reference
In-Depth Information
Background tasks and Coroutines
Next up in the fabulous journey of scripting, we will cover the treacherous realm of back-
ground tasks. We use the background tasks to start something (in the background) so that it
is runs independently of the normal game update and draw cycle.
Note
Coroutines, by default, do not run the same thread as the normal game loop. If you are not
careful, they can stop your game from running. (You can dispatch them on to separate
threads in Unity Pro to offset the work in order to improve the performance.)
For more information on Coroutines and the default execution order of methods, refer to
the article in the Unity docs at https://docs.unity3d.com/Documentation/Manual/Execu-
tionOrder.html .
The following diagram shows that we can have a second process that runs alongside our
main game:
This is usually used for systems that are continually running and not for the main events on
the screen, such as AI, a background trading system, or even a continual web-service-gath-
ering data for the game.
Unity also has the ability to synchronize these background threads with a simple function
that pauses the operation (or returns the control back to Unity). This is until the next frame
of the game is drawn ( WaitForEndOfFrame or WaitForFixedUpdate ), which
gives you a pattern like the following screenshot:
Search WWH ::




Custom Search