Unity协程(Coroutine)

Monobehaviour的函数执行顺序图
这里写图片描述

yield后面可以加的表达式

  • null - then coroutine executes the next time that it is eligible; 暂停协同程序,下一帧在继续执行
  • WaitForEndOfFrame - the coroutine executes on the frame,after all of the rendering and GUI is complete
  • WaitForFixedUpdate - causes this coroutine to execute at the next physics step, after all physics is calcuated
  • WaitForSeconds - cause the corotine not to execute for a iven game time period
  • WWW - waits for a web request to complete (resumes as if AwaiForSeconds or null)
  • 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 & Coroutine

协程其实就是一个迭代器,IEnumerator接口有两个方法Current和MoveNext(),只有当MoveNext()返回true时才会访问Current,否则回报错,迭代器犯法运行到yield return语句时,会返回一个expression表达式并保留当前代码中的位置。

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