前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#协程

C#协程

作者头像
祝你万事顺利
发布2019-05-28 13:40:57
1.8K0
发布2019-05-28 13:40:57
举报
文章被收录于专栏:Unity游戏开发Unity游戏开发

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 ,就从当前位置继续往下执行。

代码语言:javascript
复制
public interface IEnumerator
    {
        object Current { get; }

        bool MoveNext();
        void Reset();
    }

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.05.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档