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表達式並保留當前代碼中的位置。

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