天天看點

unity中的協程

關鍵詞 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 ,就從目前位置繼續往下執行。

繼續閱讀