[Unity3D] Coroutine

Table of contents

Preface

Learning source:

1. What is a coroutine?

2. Application examples of coroutines

3. How to use coroutines

3.1 Startup

3.2 End

3.3 Nesting

3.4 Note

4. Life cycle of Unity script

5. Yield quick check sheet 


Preface

Study notes are for study only, not for commercial use. If there is any infringement, please contact me to delete it.

Learning source:

Unity User Manual

Unity 协程(Coroutine)原理与用法详解https://blog.csdn.net/xinzhilinger/article/details/116240688?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168189731016800217270387%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168189731016800217270387&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-116240688-null-null.142%5Ev84%5Econtrol_2,239%5Ev2%5Einsert_chatgpt&utm_term=unity%E5%8D%8F%E7%A8%8B&spm=1018.2226.3001.4187

 Unity-Coroutine Detailed Explanationhttps://blog.csdn.net/qq_44705559/article/details/118052537

1. What is a coroutine?

A coroutine is like a function that can pause execution and return control to Unity and thenContinue execution at the next frame.

A coroutine is essentially a function declared with a return type IEnumerator and containing a yield return statement somewhere in the body.

The line where yield occurs is the pointwhere execution is paused and then resumed on the next frame.

Any variables or parameters are correctly preserved between yield statements

By default, the coroutine will resume on the frame after executing yield, but you can also use WaitForSeconds to introduce a time delay a>

Notice:

The coroutine is not multi-threaded. It runs at the same time as the main thread. It starts another piece of logical processing while the main thread is running.
It is similar to a sub-thread that handles some problems separately, and the performance overhead is small.
Unity’s coroutine will check whether the conditions are met after each frame. If it is met, the code after yield return will be executed.

2. Application examples of coroutines

The following comes from the description in  Unity Documentation Manual (V2020.1) :

Many tasks in the game need to be performed regularly, and the easiest way to think of is to include the task in the Update function.

However, typically this function will be called multiple times per second. When you don't need to repeat a task so frequently, you canplace it in a coroutine for regular updates instead of updating every frame.

An example of this might be an alert to the player when an enemy is nearby. This code might look like this:

function ProximityCheck() 
{
    for (int i = 0; i < enemies.Length; i++)
    {
        if (Vector3.Distance(transform.position, enemies[i].transform.position) < dangerDistance) {
                return true;
        }
    }
    
    return false;
}

If there are many enemies, calling this function every frame can be expensive. However, you can use a coroutine and call it every tenth of a second:

IEnumerator DoCheck() 
{
    for(;;) 
    {
        ProximityCheck();
        yield return new WaitForSeconds(.1f);
    }
}

This will significantly reduce the number of checks made without any noticeable impact on how the game is run.​ 

3. How to use coroutines

3.1 Startup

To set a coroutine to the running state, you must use a StartCoroutine function declared with a return type of IEnumerator

  • StartCoroutine (string methodName):This is the case without parameters. The coroutine is started directly through the method name (string form)
  • StartCoroutine (IEnumerator routine):Call through method form
  • StartCoroutine (string methodName, object values):Call by method name with parameters

3.2 End

You can use StopCoroutine and StopAllCoroutines to stop the coroutine . When the game object that a coroutine is attached to is disabled with SetActive(false) , the coroutine will also be stopped.

Call Destroy(example) (where example is a MonoBehaviour instance) will trigger immediately OnDisable and process the coroutine, This effectively stops the coroutine.

Finally, call OnDestroy at the end of the frame.

When disabling a MonoBehaviour by setting enabled to false on the MonoBehaviour instance, the coroutine does not Willstop.

  • StopCoroutine(string methodName):By method name (string)
  • StopCoroutine(IEnumerator routine):Called via method form
  • StopCoroutine(Coroutine routine):Close via the specified coroutine

Notice:

If we useStartCoroutine(string methodName) to start a coroutine

Then you can only use StopCoroutine(string methodName) and StopCoroutine(Coroutine routine) to end the coroutine

3.3 Nesting

Usingyield return StartCoroution(其它协程); can realize the nested use of multiple coroutines.

3.4 Note

  • Methods of type IEnumerator cannot take ref or out parameters, but can take passed references.
  • The yield statement cannot be used in the functions Update and FixedUpdate, otherwise an error will be reported, but the coroutine can be started.
  • In a coroutine, StartCoroutine() and yield return StartCoroutine() are different.
  • The former just starts a new Coroutine, and this new Coroutine executes in parallel with the existing Coroutine.
  • The latter returns a new Coroutine, which is an interrupt instruction. When the new Coroutine is completed, the existing Coroutine will be executed.

4. Life cycle of Unity script

According to the life cycle diagram, when a coroutine is set up in the program, the execution order of the program is: (assuming that the current frame is frame 1)

  1. In the first frame, the coroutine is opened in start, and the coroutine is executed (top-down). After executing the yield return line, the subsequent content is suspended.
  2. At this time, continue to execute the rest of the first frame until the execution of the first frame Update is completed.
  3. The pending content is judged between update and lateupdate of each frame to determine whether the return condition is met.
  • If the conditions are met, after the Update of the second frame and before the LateUpdate, the code after the yield return in the coroutine will be executed;
  • If the conditions are not met, the LateUpdate of frame 1 will continue to be executed.

Frame 2 is processed in the same way as Frame 1.

5. Yield quick check sheet 

yield statement Function
yield return null; Execute subsequent code in the next frame
yield return 0; Execute subsequent code in the next frame
yield return 6;(any number) Execute subsequent code in the next frame
yield break; Directly end the subsequent operations of the coroutine
yield return asyncOperation; Wait for the asynchronous operation to end before executing subsequent code
yield return StartCoroution(other coroutines); Call and execute other coroutines before executing subsequent code
yield return abc(); Wait for the abc operation to complete before executing subsequent code
yield return new WaitForEndOfFrame(); Wait for the frame to end, wait until all cameras and GUI have been rendered, and execute before the frame is displayed on the screen
yield return new WaitForSeconds(0.1f); Wait 0.1 seconds and continue execution after a specified time delay, after the frame in which all Update functions have completed calling (the time here will be affected by Time.timeScale);
yield return new WaitForSecondsRealtime(0.1f); Wait 0.1 seconds and continue execution after a specified time delay, after the frame in which all Update functions have completed calling (the time here is not affected by Time.timeScale);
yield return WaitForFixedUpdate(); Wait for the next FixedUpdate to start before executing subsequent code
yield return new WaitUntil() Will coordinate execution until the input parameter (or delegate) is true
yield return new WaitWhile() Will coordinate execution until the input parameter (or delegate) is false

Guess you like

Origin blog.csdn.net/The___sky_/article/details/130250054