unity中的协程

参考:
https://www.iteye.com/blog/dsqiu-2029701
https://www.cnblogs.com/zblade/p/9857808.html

关键词 IEnumerator

public interface IEnumerator
{
     bool MoveNext();
     void Reset();
     Object Current{get;}
}

从定义可以理解,一个迭代器,三个基本的操作:Current/MoveNext/Reset, 这儿简单说一下其操作的过程。在常见的集合中,我们使用foreach这样的枚举操作的时候,最开始,枚举数被定为在集合的第一个元素前面,Reset操作就是将枚举数返回到此位置。

迭代器在执行迭代的时候,首先会执行一个 MoveNext, 如果返回true,说明下一个位置有对象,然后此时将Current设置为下一个对象,这时候的Current就指向了下一个对象。

关键词 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
    值得注意的是 WaitForSeconds()受Time.timeScale影响,当Time.timeScale = 0f 时,yield return new WaitForSecond(x) 将不会满足。

作用

控制代码在合适的时机调用

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

Unity在每帧做的工作就是:调用 协程(迭代器)MoveNext() 方法,如果返回 true ,就从当前位置继续往下执行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章