Background tasks and coroutines
Next up in the fabulous journey of scripting, we will cover the treacherous realm of background tasks. We use the background tasks to start something (in the background) so that it runs independently of the normal game update and draw cycle.
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 webservice gathering 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) until the next frame of the game is drawn (WaitForEndOfFrame
or WaitForFixedUpdate
), which gives you a pattern similar the following diagram:
The benefit of this is that you can wait for the last update or draw cycle to finish before running your process. You might do this...