Unity – Invoke and Coroutines

      Comments Off on Unity – Invoke and Coroutines

During you’re development process you’ll probably come across scenarios where you want to have code execute after a particular amount of time has passed, or have several pieces of code that need to execute with delays. Like most large scale UI frameworks Unity can be particular about what kind of things can be accessed from secondary threads so accessing anything in the Unity Engine from a separate thread can be risky.

Normally you could solve this problem by storing a DateTime in your component for when the start, then in your update method check to see if the current date time minus the starting date time is greater than or equal to the timespan we wanted to pass, and if it has, execute our code and reset the starting date.

You can see from this how you might execute some code on a delay after a particular condition is met, but this is really clunky and messy. Luckily Unity provides a way to do this easily without the developer needing to keep track of start and end times.

Because the class inherits from MonoBehaviour we get the Invoke method, which finds a function matching the provided name and executes it after the provided number of seconds have passed. If rather than a one-time delay you wanted some code in your class to repeat every so often you can use the InvokeRepeating method.

This call to InvokeRepeating will wait for 3 seconds, then call ExecuteSomeDelayedCode the first time, and will call it again every 5 seconds after.

The CancelInvoke method can be used to remove all Invoke instructions to a particular method.

MonoBehaviour also provides a type of invocation called a Coroutine. Coroutines are slightly more complicated but are much more useful in orchestrating many delayed instructions together. Consider a game that has some scripted dialog between two characters. For this we might have 2 Text controls, each one representing a character’s dialog. We can simulate dialog between two characters using Invoke, but it starts to get messy.

Each method that adds to the conversation also invokes the next step with a slight delay so that all of the conversation text doesn’t just show up at once.

A Coroutine returns an IEnumeator and uses yield statements to control the timing and flow of the method. There are a few built in yield mechanisms in Unity, the most useful being WaitForSeconds.

The code inside of the Coroutine will execute independently of your other components just like an Invoke would, but is much easier to orchestrate than the previous example. The Coroutine will either end on its own when the code is finished, or you can forcefully stop the Coroutine with the StopCoroutine method on MonoBehaviour.