Coroutine() vs “Coroutine” in Unity

Coroutine

What is Coroutine?

According to unity,” Coroutine is special type of function which stops the execution until the define condition is met, and continue from the frame where it left off”.

In a simpler word, we can say that it is a procedural function execution, which executes the function ahead when its define conditions are met. (Doesn’t it seems like a sequence of operation executed over time.)

How to use Coroutine?

It uses IEnumerator as data type and can only be used with Monobehaviour with the StartCoroutine() function. However, StopCoroutine(string Name) is used to stop it by its name.

One more important thing that makes coroutine special is Yield instruction and its inherited child-like WaitforSeconds, WaitWhile, etc.

It is used for fetching data like JSON, XML from the server and fire some timely events.

Coroutine() vs “Coroutine”

Let us make a small script to identify the differences between this two.

using System.Collections;
using UnityEngine;

public class Test: MonoBehaviour
{
  private void Update()
  {
    if (Input.GetKeyDown(KeyCode.A))
    {
      StartCoroutine(HoldExecution());
    }
  }

  IEnumerator HoldExecution()
  {
    Debug.Log("Start Coroutine()");
    yield return new WaitForSeconds(1f);
    Debug.Log("End Coroutine()");
  }
}

Create Gameobject in the scene and applied the above script to it. After pressing play in unity editor, press “A” key to start the coroutine. It will first print the “Startcoroutine()” and after 1 second it will again print “Endcoroutine()” in the console.

This is not the idle condition, what if you want to stop the coroutine after certain condition is meetup.

using System.Collections;
using UnityEngine;

public class Test: MonoBehaviour
{
  private void Update()
  {
    if (Input.GetKeyDown(KeyCode.A))
    {     
      StartCoroutine(HoldExecution());
    }
if (Input.GetKeyDown(KeyCode.X)) { Debug.Log("Stop Coroutine()"); StopCoroutine(HoldExecution()); } } IEnumerator HoldExecution() { Debug.Log("Start Coroutine()"); yield return new WaitForSeconds(1f); Debug.Log("End Coroutine()"); } }

Run the above code and try to stop coroutine before it prints the end statement in the console. Did you see what printed in the console logs?. Even if you pressed the key “X”, before it finished, it did not stop, but also print the end statement. So, to overcome this situation we used the “coroutine” to make sure it will stop just after our stop command.

using System.Collections;
using UnityEngine;

public class Test: MonoBehaviour
{
   private void Update()    
  {
    if (Input.GetKeyDown(KeyCode.A))        
    {            
      StartCoroutine("HoldExecution");        
    }
      
    if (Input.GetKeyDown(KeyCode.X))        
    {           
      Debug.Log("Stop Coroutine()");
      StopCoroutine("HoldExecution");     
    }    
  }

  IEnumerator HoldExecution()  
  {       
    Debug.Log("Start Coroutine()");       
    yield return new WaitForSeconds(1f);        
    Debug.Log("End Coroutine()");    
  }
}

Run above script and press key “X” before it ends. It just did not print the end statement. So, it will be more useful in some game scenario. However, it is important to note that, If you change your coroutine name in the game, then it will be difficult to trace changes.

To overcome this situation we used its reference to manage that function execution.

using System.Collections;
using UnityEngine;

public class Test: MonoBehaviour
{    
  Coroutine logCoroutine;

  private void Update()    
  {
    if (Input.GetKeyDown(KeyCode.A))      
    {           
      logCoroutine = StartCoroutine(HoldExecution());      
    }

    if (Input.GetKeyDown(KeyCode.X))      
    {
      if (logCoroutine != null)            
      {              
        Debug.Log("Stop Coroutine()");               
        StopCoroutine(logCoroutine);               
        logCoroutine = null;            
      }       
    }    
  }

  IEnumerator HoldExecution()    
  {        
    Debug.Log("Start Coroutine()");        
    yield return new WaitForSeconds(1f);
    Debug.Log("End Coroutine()");    
  }
}

We can assign it in reference and use it to stop it. You can use this Both way, but I normally prefer the above code to avoid any painful situation later in the project.

In conclusion, we can say that both ways for Startcoroutine are depended on the situation of your game. But the reference way you can hold command in your hand.

Leave a Reply