C#协程

2019-05-21  本文已影响0人  祝你万事顺利

Unity中协程的执行原理

UnityGems.com给出了协程的定义:

A coroutine is a function that is executed partially and, presuming suitable conditions are met, will be resumed at some point in the future until its work is done.
即协程是一个分部执行,遇到条件(yield return 语句)会挂起,直到条件满足才会被唤醒继续执行后面的代码。
Unity在每一帧(Frame)都会去处理对象上的协程。Unity主要是在Update后去处理协程(检查协程的条件是否满足)

life.png

整理得到:

通过设置MonoBehaviour脚本的enabled对协程是没有影响的,但如果 gameObject.SetActive(false) 则已经启动的协程则完全停止了,即使在Inspector把gameObject 激活还是没有继续执行。也就说协程虽然是在MonoBehvaviour启动的(StartCoroutine)但是协程函数的地位完全是跟MonoBehaviour是一个层次的,不受MonoBehaviour的状态影响,但跟MonoBehaviour脚本一样受gameObject 控制,也应该是和MonoBehaviour脚本一样每帧“轮询” yield 的条件是否满足。

yield 后面可以有的表达式:
a) null - the coroutine executes the next time that it is eligible
b) WaitForEndOfFrame - the coroutine executes on the frame, after all of the rendering and GUI is complete
c) WaitForFixedUpdate - causes this coroutine to execute at the next physics step, after all physics is calculated
d) WaitForSeconds - causes the coroutine not to execute for a given game time period
e) WWW - waits for a web request to complete (resumes as if WaitForSeconds or null)
f) Another coroutine - in which case the new coroutine will run to completion before the yielder is resumed

逐帧检测:
IEnumerator & Coroutine

协程其实就是一个IEnumerator(迭代器),IEnumerator 接口有两个方法 Current 和 MoveNext() ,前面介绍的 TaskManager 就是利用者两个方法对协程进行了管理,只有当MoveNext()返回 true时才可以访问 Current,否则会报错。迭代器方法运行到 yield return 语句时,会返回一个expression表达式并保留当前在代码中的位置。 当下次调用迭代器函数时执行从该位置重新启动。
Unity在每帧做的工作就是:调用 协程(迭代器)MoveNext() 方法,如果返回 true ,就从当前位置继续往下执行。

public interface IEnumerator
    {
        object Current { get; }

        bool MoveNext();
        void Reset();
    }

资料参考:http://dsqiu.iteye.com/blog/2029701

上一篇下一篇

猜你喜欢

热点阅读