TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Unity Coroutines

Unity Coroutines with Introduction, Installing, GameObject, First Unity Project, Unity 2D, Sprite Unity, Loops, If Statement, Data Types, Swith Statements, Unity UI, Unity Asset Store etc.

<< Back to UNITY

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).

IEnumerator MyCoroutineMethod() {
   // Your code here...
   
   yield return null;
}

Example:

IEnumerator MyCoroutine()
{
  Debug.Log("Hello world");
  yield return null; 
//yield must be used before any return
}

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:

StartCoroutine( string functionName)

Example:

StartCoroutine("myCoroutine")

IEnumerator Based:

Syntax:

StartCoroutine(IEnumerator e)

Example:

StartCoroutine(myCoroutine())

Stop the Coroutine

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

String Based:

Syntax:

StopCoroutine( string functionName)

Example:

StopCoroutine("myCoroutine")

IEnumerator Based:

Syntax:

StopCoroutine(IEnumerator e)

Example:

StopCoroutine(myCoroutine())

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:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColorChanger : MonoBehaviour
{
    
private SpriteRenderer sr;

public Color color1;
public Color color2;

void Start () {
   sr = GetComponent();
   StartCoroutine(ChangeColor());
}

 IEnumerator ChangeColor() {
   
   while (true) {
      
      if (sr.color == color1)
         sr.color = color2;
      
      else
         sr.color = color1;
      
      yield return new WaitForSeconds(3);
   }
}
}

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeChange : MonoBehaviour
{
    IEnumerator WaitAndPrint()
    {
        // suspend execution for 5 seconds
        yield return new WaitForSeconds(5);
        print("WaitAndPrint " + Time.time);
    }

    IEnumerator Start()
    {
        print("Starting " + Time.time);

        // Start function WaitAndPrint as a coroutine
        yield return StartCoroutine("WaitAndPrint");
        print("Done " + Time.time);
    }
}

Output:

Unity Coroutines
Next TopicUnity UI




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf