When to use a Coroutine in Unity
Consider using a Coroutine whenever you need to create an action that must pause, perform a series of steps in sequence, or run a task that you know will take more than a single frame.
Here are a few examples:
- Putting an object in a specific location.
- Providing an object with a list of tasks to complete (like in the To-Do list example earlier).
- Fading in and out of visuals or audio.
- Waiting for the resources to load.
These are the kinds of tasks that Coroutines excel at.
How to Write a Coroutine
A Coroutine is structured similarly to a regular function, with a few key differences.
First, the return type of a Coroutine must be IEnumerator, as shown below:
IEnumerator MyCoroutine()
{
// Code goes here!
}
Don't worry if you're unfamiliar with IEnumerator.
All you need to know right now is that this is how Unity divides the function's execution across multiple frames.
A Coroutine, like any other function, accepts parameters.
IEnumerator MyCoroutine(int number)
{
number++;
// Code goes here!
}
Variables initialized within the Coroutine will retain their value for the duration.
In addition, unlike regular functions, Coroutines allow you to use a yield statement to pause the code while it is running.
How to Pause a Coroutine in Unity (Yield)
There are several types of yield statements that will pause a Coroutine, and which one we use depends on how long we want the method to be paused.
Yield statements indicate that the method is an iterator and will execute across multiple frames, whereas return, like in a regular function, terminates execution at that point and returns control to the calling method.
The difference is that Unity knows to continue the method where it left off with a Coroutine.
We can use yield in different ways:
- yield return null - This will Resume execution after All Update functions have been called, on the next frame.
- yield return new WaitForSeconds(t) - Resumes execution after (Approximately) t seconds.
- yield return new WaitForEndOfFrame() - Resumes execution after all cameras and GUI were rendered.
- yield return new WaitForFixedUpdate() - Resumes execution after all FixedUpdates have been called on all scripts.
- yield return new WWW(url) - This will resume execution after the web resource at URL was downloaded or failed.
How to start a Coroutine
There are two methods to start a Coroutine.
String Based:
void Start()
{
StartCoroutine("MyCoroutine");
}
IEnumerator MyCoroutine()
{
// Code goes here!
}
IEnumerator Based:
void Start()
{
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
// Code goes here!
}
How to stop a Coroutine
Coroutines terminate themselves once their code has been executed. A Coroutine does not need to be explicitly terminated. However, you may want to manually terminate a Coroutine before it completes. This can be accomplished in a variety of ways.
String Based:
StopCoroutine("myCoroutine")
IEnumerator Based:
StopCoroutine(myCoroutine())
Coroutines vs Invoke vs Async
Coroutines are useful, but there may be times when other options are preferable.
For example, if you want to delay the start of a function, Invoke will do it, whereas Invoke Repeating is a good choice for repeatedly performing the same function.
In Unity, you can also use Async and Await functions, which work similarly to Coroutines.
One of the most significant differences between Async and Await functions and Coroutines is that they can return a value, whereas Coroutines cannot.
Frequently Asked Questions
How do you write Coroutines in Unity?
There are two methods to start a Coroutine.
- string, like this: void Start() { StartCoroutine("MyCoroutine"); }
- IEnumerator MyCoroutine() { // Code goes here!}
Why are Coroutines useful?
Producer/consumer patterns can be implemented using coroutines.
Are Coroutines fast?
Coroutines are super fast and light.
Conclusion
In this article, we have extensively discussed the Coroutines in Unity, and how to write Coroutine ( starting, stopping, and pausing a Coroutine). We had also discussed Coroutines’ differences with Invoke and Async.
We hope that this blog has helped you enhance your knowledge of Coroutines in Unity and if you would like to learn more, check out our articles on our website.
Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.
Do upvote our blogs if you find them helpful and engaging!
Happy Learning!