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

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