You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Coroutine and simple examples

Ben Liu
Ben Liu

What is coroutine, TL;DR:

Simply put, coroutine in Unity is a piece of code (normally a method), and within that code there is a place to pause at each frame, and run again in the next frame until certain condition is met.

When will need coroutine:

There are a couple of scenarios:

  • When you have a large computing job which can't be finished in one frame, such as path finding. Normally we split the function into different frames.
  • When you have a trigger event, nothing will be done until it is triggered. e.g. when a game object moves to a specific location.
  • Asynchronous jobs, such as fetching resources online, etc

Example

The following example shows how to set up a timer using coroutine:

private float countDown = 0;

public IEnumerator StartCountdown(float countdownValue = 10) {
	countDown = countdownValue;
	while (countDown > 0) {
		Debug.Log("Countdown: " + countDown);
		yield return new WaitForSeconds(1.0f);
		countDown--;
	}
}

// to use
StartCoroutine(StartCountdown());
// or 
StartCoroutine(StartCountdown(10));

// output
Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

Return value of coroutine

Coroutine returns an IEnumerator, which is an iterator. The following are some different uses of coroutine:

// Continue after a specified time delay (2s in here), after all Update 
// functions have been called for the frame
yield return new WaitForSeconds(2);

// Continue after all FixedUpdate has been called on all scripts
yield return new WaitForFixedUpdate(); 

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp