Unity-coroutine principle

 Knowledge point-the essence of coroutines

Knowledge point 2 The coroutine ontology is the embodiment of the iterator method

 1. Coroutine function body

Define a coroutine function, and a class:

 If we call the coroutine Test function separately, no statement will be executed.

 Nothing is output.

 Why can't we call the coroutine function alone, need to use the StartCoroutine() function?

Because the function in Test is not actually executed at this time, it just returns an iterator object.

 We can save this object and execute it without the coroutine scheduler.

 The internal method of IEnumerator, the properties are as follows.

Use the MoveNext() method in IEnumerator. 

 It was found that it was printed.

Then call its Current property and find that the return value of yield return is printed.

 Execute the above methods and properties multiple times.

 The running results are as follows.

 Even we can call the value returned by Current.

 

 10 is printed out.

 The essence of coroutine: coroutine function body (iterator) + coroutine scheduler

 Another problem comes, we can use MoveNext() and Current to execute the coroutine function step by step. But what if there are n yield returns in the coroutine function? Write n MoveNext() and Curren?

Note: MoveNext() returns a bool value, returns true when there is still executable content in the coroutine function, and does not return flase.

 Execute everything through a while loop.

 The result of the operation is as follows:

 2. Coroutine scheduler

 

 

 

Guess you like

Origin blog.csdn.net/qq_42705793/article/details/127657926