Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Jun 28, 2024

Coroutines in Unity

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

If you're new to Unity, you may have written a lot of your code within the Update function.

This could imply that you use boolean conditions to manage states and if conditions to call functions and deploy different blocks of code at different times. That's fine, especially if you're just starting with scripting in Unity.

However, suppose you've tried to delay a function or let it have to wait for another action to finish or pause it halfway through, or queue up a series of actions to take place one after the other. In that case, you may have found it difficult to do so inside Update or using a regular function. But don't worry, because the Coroutines will save the day!

What are Coroutines in Unity

Inside of the Update code, it is typical to execute all code at once during the current frame.

On the other hand, coroutines allow you to run game logic across multiple frames.

Simply put, you can pause a function and instruct it to wait for a condition or action to occur before continuing. This allows you to divide its functionality into several steps that can be performed sequentially.

This is fantastic for performing actions that would be impossible, inefficient, or simply difficult to perform within Update alone.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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 AlgorithmsCompetitive ProgrammingJavaScriptSystem 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 problemsinterview experiences, and interview bundle for placement preparations.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Topics covered
1.
Introduction
2.
What are Coroutines in Unity
3.
When to use a Coroutine in Unity
4.
How to Write a Coroutine
5.
How to Pause a Coroutine in Unity (Yield)
6.
How to start a Coroutine
7.
How to stop a Coroutine
8.
Coroutines vs Invoke vs Async
9.
Frequently Asked Questions
9.1.
How do you write Coroutines in Unity?
9.2.
Why are Coroutines useful?
9.3.
Are Coroutines fast?
10.
Conclusion