The essence and principle of Unity_coroutine_execution order of coroutine

If you understand C# iterators, you are no stranger to IEnumrator and yield return classes and syntactic sugar statements

IEnumrator is an interface that implements iterators must inherit 

Yield return is the syntactic sugar of C#. We don't need to implement the iterator by ourselves. We can directly implement the iterator through this line of code.

In the interface of the iterator, two key members, the MoveNext() function, the Current property is the core of the iterator through the cooperation of these two members.

You can implement, for example, iteration over a custom class

So, let's split the Unity coroutine

Coroutines can be divided into two parts:

1. Coroutine function body

2. Coroutine scheduler

The coroutine function body is essentially an iterator function. The iterator function returns the content step by step, and Unity's coroutine scheduler implements internal rules based on the content returned by yield return.

MoveNext();//will execute the logic until the content in the function encounters yield return

Current;//Get the content returned by yield return

That is to say, the coroutine function body realizes the "step-by-step" operation of executing code, and Unity's coroutine scheduler internally realizes the "time-sharing" operation according to the return value. The combination of the two constitutes our coroutine! !!

Summarize:

        You can simplify the understanding of the iterator function.
        C# sees the iterator function and yield return syntactic sugar,
        which will turn the original function into "several parts".
        We can traverse these "several parts" from top to bottom through the iterator to execute
        . The purpose of time-sharing execution of the logic in a function is achieved

        The coroutine scheduler uses the content returned by the iterator function for subsequent processing.
        For example, the coroutine scheduler in Unity
        determines when to continue executing the "next part" of the iterator function next time based on the content returned by yield return.

        In theory, we can use the characteristics of the iterator function to implement the coroutine scheduler to replace the scheduler that comes with Unity.

PS: Coroutines also have a certain execution order. Through MonoBehaviour, you can intuitively see the execution order of each yield return statement.

 

Guess you like

Origin blog.csdn.net/m0_69778537/article/details/131874640