Javatpoint Logo
Javatpoint Logo

Unity Coroutines

A coroutine is a function that allows pausing its execution and resuming from the same point after a condition is met. We can say, a coroutine is a special type of function used in unity to stop the execution until some certain condition is met and continues from where it had left off.

This is the main difference between C# functions and Coroutines functions other than the syntax. A typical function can return any type, whereas coroutines must return an IEnumerator, and we must use yield before return.

Coroutines can be used for two reasons: asynchronous code and code that needs to compute over several frames.

So basically, coroutines facilitate us to break work into multiple frames, you might have thought we can do this using Update function. You are right, but we do not have any control over the Update function. Coroutine code can be executed on-demand or at a different frequency (e.g., every 5 seconds instead of every frame).

Example:

Here, the yield is a special return statement. It is what tells Unity to pause the script and continue on the next frame.

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.

Start the Coroutine

We can start Coroutine in two ways:

String Based:

Syntax:

Example:

IEnumerator Based:

Syntax:

Example:

Stop the Coroutine

We can stop the Coroutine using same ways; here instead of calling StartCoroutine, we will use StopCoroutine:

String Based:

Syntax:

Example:

IEnumerator Based:

Syntax:

Example:

Example 1

Let's see one simple example to see how coroutine works. For that create a circle sprite. Then create one script file, name it as ColorChanger.cs and copy the following code:

Attach this script file to the Sprite's component. And select two colors in color1 and color2 variable.

Unity Coroutines

Now, when you play this game, our circle object will switch between the two colors in 3 seconds intervals.

Output:

Unity Coroutines

Example 2

Output:

Unity Coroutines
Next TopicUnity UI





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA