SoFunction
Updated on 2025-03-06

Detailed explanation of how to use coroutine IEnumerator in Unity

In Unity, general methods are executed sequentially, and general methods are executed in one frame. When the method we write takes a certain amount of time, the frame rate will drop and the picture will be stuck. When we call a method to make an object disappear slowly, in addition to performing related operations in Update, Unity also provides a more convenient method, which is coroutine.

Normally, if we want an object to disappear gradually, we hope that the method can be called in one go to achieve the effect we want in subsequent execution of the program.

We hope the code can be written as follows:

void Fade() 
{
    for (float f = 1f; f >= 0; f -= 0.1f) 
    {
        Color c = ;
         = f;
         = c;
    }
}

However, this method will be executed in one frame when called, and the expected effect cannot be achieved. If you rewrite the method and put it in the Update function, you can achieve the effect we expected, but it is not elegant enough.

float time = 0f;
float fadeTime = 2f;
void Fade() 
{
    time += ;
    Color c = ;
     = 1f - time/fadeTime;
     = c;
}

The coroutine method in Unity can be paused at any position or at any time through the special property yield. It can also be continued after a specified time or event without affecting the result of the last execution, providing great convenience and practicality.
A coroutine will create a new (pseudo) new thread to execute each time it is executed without affecting the execution of the main thread.

Just like the above method, we can use coroutines to achieve the effect we want more conveniently.

void Fade() 
{
    for (float f = 1f; f >= 0; f -= 0.1f) 
    {
        Color c = ;
         = f;
         = c;
        yield return null;//The next frame continues to execute the for loop        yield return new WaitForSeconds(0.1f);//Continue to execute the for loop after 0.1 seconds    }
}

We call coroutine functions through StartCoroutine() function.

It is worth noting that coroutines do not open up new threads in Unity to execute, and their execution still occurs in the main thread. When we have a relatively time-consuming operation, we can distribute the operation to several frames or seconds, without waiting for the operation to be completed within one frame before performing other operations.
If we need to execute a loop:

IEnumerator CaculateResult()
{
    for (int i = 0; i < 10000; i++)
    {
        //Internal loop calculation        //The yield here will make the internal loop calculation executed once per frame, without waiting for 10,000 loops to end before jumping out        //yield return null;
    }
    //If the internal yield operation is cancelled and only write the yield operation outside the for loop, 10,000 loops will be executed before the end, which is equivalent to directly calling a function, not a coroutine.    //yield return null;
}

There are two methods to call coroutine, namely StartCoroutine (/The method is called directly here and the parameters are added/), and the other is StartCoroutine (/The method name of the string is filled in here and the method parameters/). The advantage of the first method is that it can call methods with multiple parameters, while the latter method can only call coroutine methods without parameters or with only one parameter. However, the first method cannot end the coroutine through StopCoroutine (/Fill in "the method name of the string"/), and can only end through StopAllCoroutines. The latter type can end the call to the executing coroutine through StopCoroutine.

During the implementation of coroutines, we need to pay attention to the timing of yield calls. When performing more complex calculations, if there is no strict order in time, we can execute a loop once per frame to complete the calculation, or execute a specified number of loops per frame to prevent lags during program operation.

Introduction to yield return:

yield return null; // Execute subsequent code in the next frameyield return 0; //Execute subsequent code in the next frameyield return 6;//(Arbitrary number) Execute subsequent code in the next frameyield break; //Turn the subsequent operations of the coroutineyield return asyncOperation;//When the asynchronous operation is completed before executing the subsequent codeyield return StartCoroution(/*A coroutine*/);//Waiting for a coroutine to complete execution before executing the subsequent codeyield return WWW();//Wait until the WWW operation is completed before executing the subsequent codeyield return new WaitForEndOfFrame();//Waiting for the frame to end, wait until all cameras and GUIs are rendered, and execute before the frame is displayed on the screenyield return new WaitForSeconds(0.3f);//Wait 0.3 seconds, continue to execute after a specified time delay, after all Update functions complete the call frame (the time here will be affected);yield return new WaitForSecondsRealtime(0.3f);//Wait 0.3 seconds, continue to execute after a specified time delay, after all Update functions complete the frame of call (the time here is not affected);yield return WaitForFixedUpdate();//Waiting for the next FixedUpdate start before executing the subsequent codeyield return new WaitUntil()//The execution will be carried out together until when the input parameter (or delegate) is true... For example: yield return new WaitUntil(() => frame >= 10);yield return new WaitWhile()//The execution will be carried out together until when the input parameter (or delegate) is false... For example: yield return new WaitWhile(() => frame < 10);

When a coroutine in a script is executed, if we set the enable of the script to false, the coroutine will not stop. It will stop only if the object that mounts the script is set to SetActive(false).

After calling StartCoroutine(), Unity will not wait for the contents in the coroutine to return, and will execute subsequent code immediately.

Although coroutines are very convenient and flexible, improper use will cause unforeseen consequences for the program. Please consider carefully before using them.

This is the article about the detailed explanation of how to use coroutine IEnumerator in Unity. For more related Unity coroutine IEnumerator content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!