Unity協程(Coroutine)原理深刻剖析

Unity協程(Coroutine)原理深刻剖析html

 

 By D.S.Qiuweb

尊重他人的勞動,支持原創,轉載請註明出處:http.dsqiu.iteye.comexpress

        

        記得去年6月份剛開始實習的時候,當時要我寫網絡層的結構,用到了協程,當時有點懵,徹底不知道Unity協程的執行機制是怎麼樣的,只是知道函數的返回值是IEnumerator類型,函數中使用yield return ,就能夠經過StartCoroutine調用了。後來也是一直稀裏糊塗地用,上網google些基本都是例子,不多能幫助深刻理解Unity協程的原理的。網絡

        本文只是從Unity的角度去分析理解協程的內部運行原理,而不是從C#底層的語法實現來介紹(後續有須要再進行介紹),一共分爲三部分:異步

                  線程(Thread)和協程(Coroutine) 函數

                  Unity中協程的執行原理工具

                        IEnumerator & Coroutine測試

        以前寫過一篇《Unity協程(Coroutine)管理類——TaskManager工具分享》主要是介紹TaskManager實現對協程的狀態控制,沒有Unity後臺實現的協程的原理進行深究。雖然以前本身對協程還算有點了解了,可是對Unity如何執行協程的仍是一片空白,在UnityGems.com上看到兩篇講解Coroutine,如數家珍,當我看到Advanced Coroutine後面的Hijack類時,頓時以爲十分精巧,眼前一亮,遂動了寫文分享之。ui

 

線程(Thread)和協程(Coroutine)      this

        D.S.Qiu以爲使用協程的做用一共有兩點:1)延時(等待)一段時間執行代碼;2)等某個操做完成以後再執行後面的代碼。總結起來就是一句話:控制代碼在特定的時機執行。

        不少初學者,都會下意識地以爲協程是異步執行的,都會以爲協程是C# 線程的替代品,是Unity不使用線程的解決方案。

        因此首先,請你牢記:協程不是線程,也不是異步執行的。協程和 MonoBehaviour 的 Update函數同樣也是在MainThread中執行的。使用協程你不用考慮同步和鎖的問題。

 

Unity中協程的執行原理

        UnityGems.com給出了協程的定義:

               A coroutine is a function that is executed partially and, presuming suitable conditions are met, will be resumed at some point in the future until its work is done.

        即協程是一個分部執行,遇到條件(yield return 語句)會掛起,直到條件知足纔會被喚醒繼續執行後面的代碼。

        Unity在每一幀(Frame)都會去處理對象上的協程。Unity主要是在Update後去處理協程(檢查協程的條件是否知足),但也有寫特例:

        從上圖的剖析就明白,協程跟Update()其實同樣的,都是Unity每幀對會去處理的函數(若是有的話)。若是MonoBehaviour 是處於激活(active)狀態的並且yield的條件知足,就會協程方法的後面代碼。還能夠發現:若是在一個對象的前期調用協程,協程會當即運行到第一個 yield return 語句處,若是是 yield return null ,就會在同一幀再次被喚醒。若是沒有考慮這個細節就會出現一些奇怪的問題『1』。

        『1』注 圖和結論都是從UnityGems.com 上得來的,通過下面的驗證發現與實際不符,D.S.Qiu用的是Unity 4.3.4f1 進行測試的。通過測試驗證,協程至少是每幀的LateUpdate()後去運行。

        下面使用 yield return new WaitForSeconds(1f); 在Start,Update 和 LateUpdate 中分別進行測試:

C#代碼   收藏代碼
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class TestCoroutine : MonoBehaviour {  
  5.   
  6.     private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once  
  7.     private bool isUpdateCall = false;  
  8.     private bool isLateUpdateCall = false;  
  9.     // Use this for initialization  
  10.     void Start () {  
  11.         if (!isStartCall)  
  12.         {  
  13.             Debug.Log("Start Call Begin");  
  14.             StartCoroutine(StartCoutine());  
  15.             Debug.Log("Start Call End");  
  16.             isStartCall = true;  
  17.         }  
  18.       
  19.     }  
  20.     IEnumerator StartCoutine()  
  21.     {  
  22.           
  23.         Debug.Log("This is Start Coroutine Call Before");  
  24.         yield return new WaitForSeconds(1f);  
  25.         Debug.Log("This is Start Coroutine Call After");  
  26.              
  27.     }  
  28.     // Update is called once per frame  
  29.     void Update () {  
  30.         if (!isUpdateCall)  
  31.         {  
  32.             Debug.Log("Update Call Begin");  
  33.             StartCoroutine(UpdateCoutine());  
  34.             Debug.Log("Update Call End");  
  35.             isUpdateCall = true;  
  36.         }  
  37.     }  
  38.     IEnumerator UpdateCoutine()  
  39.     {  
  40.         Debug.Log("This is Update Coroutine Call Before");  
  41.         yield return new WaitForSeconds(1f);  
  42.         Debug.Log("This is Update Coroutine Call After");  
  43.     }  
  44.     void LateUpdate()  
  45.     {  
  46.         if (!isLateUpdateCall)  
  47.         {  
  48.             Debug.Log("LateUpdate Call Begin");  
  49.             StartCoroutine(LateCoutine());  
  50.             Debug.Log("LateUpdate Call End");  
  51.             isLateUpdateCall = true;  
  52.         }  
  53.     }  
  54.     IEnumerator LateCoutine()  
  55.     {  
  56.         Debug.Log("This is Late Coroutine Call Before");  
  57.         yield return new WaitForSeconds(1f);  
  58.         Debug.Log("This is Late Coroutine Call After");  
  59.     }  
  60. }  

 獲得日誌輸入結果以下:

 

        而後將yield return new WaitForSeconds(1f);改成 yield return null; 發現日誌輸入結果和上面是同樣的,沒有出現上面說的狀況:

C#代碼   收藏代碼
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class TestCoroutine : MonoBehaviour {  
  5.   
  6.     private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once  
  7.     private bool isUpdateCall = false;  
  8.     private bool isLateUpdateCall = false;  
  9.     // Use this for initialization  
  10.     void Start () {  
  11.         if (!isStartCall)  
  12.         {  
  13.             Debug.Log("Start Call Begin");  
  14.             StartCoroutine(StartCoutine());  
  15.             Debug.Log("Start Call End");  
  16.             isStartCall = true;  
  17.         }  
  18.       
  19.     }  
  20.     IEnumerator StartCoutine()  
  21.     {  
  22.           
  23.         Debug.Log("This is Start Coroutine Call Before");  
  24.         yield return null;  
  25.         Debug.Log("This is Start Coroutine Call After");  
  26.              
  27.     }  
  28.     // Update is called once per frame  
  29.     void Update () {  
  30.         if (!isUpdateCall)  
  31.         {  
  32.             Debug.Log("Update Call Begin");  
  33.             StartCoroutine(UpdateCoutine());  
  34.             Debug.Log("Update Call End");  
  35.             isUpdateCall = true;  
  36.         }  
  37.     }  
  38.     IEnumerator UpdateCoutine()  
  39.     {  
  40.         Debug.Log("This is Update Coroutine Call Before");  
  41.         yield return null;  
  42.         Debug.Log("This is Update Coroutine Call After");  
  43.     }  
  44.     void LateUpdate()  
  45.     {  
  46.         if (!isLateUpdateCall)  
  47.         {  
  48.             Debug.Log("LateUpdate Call Begin");  
  49.             StartCoroutine(LateCoutine());  
  50.             Debug.Log("LateUpdate Call End");  
  51.             isLateUpdateCall = true;  
  52.         }  
  53.     }  
  54.     IEnumerator LateCoutine()  
  55.     {  
  56.         Debug.Log("This is Late Coroutine Call Before");  
  57.         yield return null;  
  58.         Debug.Log("This is Late Coroutine Call After");  
  59.     }  
  60. }  

        『今天意外發現Monobehaviour的函數執行順序圖,發現協程的運行確實是在LateUpdate以後,下面附上:』
                                                                       增補於:03/12/2014 22:14
 

        前面在介紹TaskManager工具時,說到MonoBehaviour 沒有針對特定的協程提供Stop方法,其實否則,能夠經過MonoBehaviour enabled = false 或者 gameObject.active = false 就能夠中止協程的執行『2』。

        通過驗證,『2』的結論也是錯誤的,正確的結論是,MonoBehaviour.enabled = false 協程會照常運行,但 gameObject.SetActive(false) 後協程卻所有中止,即便在Inspector把  gameObject 激活仍是沒有繼續執行:

C#代碼   收藏代碼
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class TestCoroutine : MonoBehaviour {  
  5.   
  6.     private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once  
  7.     private bool isUpdateCall = false;  
  8.     private bool isLateUpdateCall = false;  
  9.     // Use this for initialization  
  10.     void Start () {  
  11.         if (!isStartCall)  
  12.         {  
  13.             Debug.Log("Start Call Begin");  
  14.             StartCoroutine(StartCoutine());  
  15.             Debug.Log("Start Call End");  
  16.             isStartCall = true;  
  17.         }  
  18.       
  19.     }  
  20.     IEnumerator StartCoutine()  
  21.     {  
  22.           
  23.         Debug.Log("This is Start Coroutine Call Before");  
  24.         yield return new WaitForSeconds(1f);  
  25.         Debug.Log("This is Start Coroutine Call After");  
  26.              
  27.     }  
  28.     // Update is called once per frame  
  29.     void Update () {  
  30.         if (!isUpdateCall)  
  31.         {  
  32.             Debug.Log("Update Call Begin");  
  33.             StartCoroutine(UpdateCoutine());  
  34.             Debug.Log("Update Call End");  
  35.             isUpdateCall = true;  
  36.             this.enabled = false;  
  37.             //this.gameObject.SetActive(false);  
  38.         }  
  39.     }  
  40.     IEnumerator UpdateCoutine()  
  41.     {  
  42.         Debug.Log("This is Update Coroutine Call Before");  
  43.         yield return new WaitForSeconds(1f);  
  44.         Debug.Log("This is Update Coroutine Call After");  
  45.         yield return new WaitForSeconds(1f);  
  46.         Debug.Log("This is Update Coroutine Call Second");  
  47.     }  
  48.     void LateUpdate()  
  49.     {  
  50.         if (!isLateUpdateCall)  
  51.         {  
  52.             Debug.Log("LateUpdate Call Begin");  
  53.             StartCoroutine(LateCoutine());  
  54.             Debug.Log("LateUpdate Call End");  
  55.             isLateUpdateCall = true;  
  56.   
  57.         }  
  58.     }  
  59.     IEnumerator LateCoutine()  
  60.     {  
  61.         Debug.Log("This is Late Coroutine Call Before");  
  62.         yield return null;  
  63.         Debug.Log("This is Late Coroutine Call After");  
  64.     }  
  65. }  

 先在Update中調用 this.enabled = false; 獲得的結果:

而後把 this.enabled = false; 註釋掉,換成 this.gameObject.SetActive(false); 獲得的結果以下:

       整理獲得:經過設置MonoBehaviour腳本的enabled對協程是沒有影響的,但若是 gameObject.SetActive(false) 則已經啓動的協程則徹底中止了,即便在Inspector把gameObject 激活仍是沒有繼續執行。也就說協程雖然是在MonoBehvaviour啓動的(StartCoroutine)可是協程函數的地位徹底是跟MonoBehaviour是一個層次的,不受MonoBehaviour的狀態影響,但跟MonoBehaviour腳本同樣受gameObject 控制,也應該是和MonoBehaviour腳本同樣每幀「輪詢」 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 & Coroutine

        協程其實就是一個IEnumerator(迭代器),IEnumerator 接口有兩個方法 Current 和 MoveNext() ,前面介紹的 TaskManager 就是利用者兩個方法對協程進行了管理,只有當MoveNext()返回 true時才能夠訪問 Current,不然會報錯。迭代器方法運行到 yield return 語句時,會返回一個expression表達式並保留當前在代碼中的位置。 當下次調用迭代器函數時執行從該位置從新啓動。

        Unity在每幀作的工做就是:調用 協程(迭代器)MoveNext() 方法,若是返回 true ,就從當前位置繼續往下執行。

 

Hijack

         這裏在介紹一個協程的交叉調用類 Hijack(參見附件):

C#代碼   收藏代碼
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using UnityEngine;  
  5. using System.Collections;  
  6.    
  7. [RequireComponent(typeof(GUIText))]  
  8. public class Hijack : MonoBehaviour {  
  9.    
  10.     //This will hold the counting up coroutine  
  11.     IEnumerator _countUp;  
  12.     //This will hold the counting down coroutine  
  13.     IEnumerator _countDown;  
  14.     //This is the coroutine we are currently  
  15.     //hijacking  
  16.     IEnumerator _current;  
  17.    
  18.     //A value that will be updated by the coroutine  
  19.     //that is currently running  
  20.     int value = 0;  
  21.    
  22.     void Start()  
  23.     {  
  24.         //Create our count up coroutine  
  25.         _countUp = CountUp();  
  26.         //Create our count down coroutine  
  27.         _countDown = CountDown();  
  28.         //Start our own coroutine for the hijack  
  29.         StartCoroutine(DoHijack());  
  30.     }  
  31.    
  32.     void Update()  
  33.     {  
  34.         //Show the current value on the screen  
  35.         guiText.text = value.ToString();  
  36.     }  
  37.    
  38.     void OnGUI()  
  39.     {  
  40.         //Switch between the different functions  
  41.         if(GUILayout.Button("Switch functions"))  
  42.         {  
  43.             if(_current == _countUp)  
  44.                 _current = _countDown;  
  45.             else  
  46.                 _current = _countUp;  
  47.         }  
  48.     }  
  49.    
  50.     IEnumerator DoHijack()  
  51.     {  
  52.         while(true)  
  53.         {  
  54.             //Check if we have a current coroutine and MoveNext on it if we do  
  55.             if(_current != null && _current.MoveNext())  
  56.             {  
  57.                 //Return whatever the coroutine yielded, so we will yield the  
  58.                 //same thing  
  59.                 yield return _current.Current;  
  60.             }  
  61.             else  
  62.                 //Otherwise wait for the next frame  
  63.                 yield return null;  
  64.         }  
  65.     }  
  66.    
  67.     IEnumerator CountUp()  
  68.     {  
  69.         //We have a local increment so the routines  
  70.         //get independently faster depending on how  
  71.         //long they have been active  
  72.         float increment = 0;  
  73.         while(true)  
  74.         {  
  75.             //Exit if the Q button is pressed  
  76.             if(Input.GetKey(KeyCode.Q))  
  77.                 break;  
  78.             increment+=Time.deltaTime;  
  79.             value += Mathf.RoundToInt(increment);  
  80.             yield return null;  
  81.         }  
  82.     }  
  83.    
  84.     IEnumerator CountDown()  
  85.     {  
  86.         float increment = 0f;  
  87.         while(true)  
  88.         {  
  89.             if(Input.GetKey(KeyCode.Q))  
  90.                 break;  
  91.             increment+=Time.deltaTime;  
  92.             value -= Mathf.RoundToInt(increment);  
  93.             //This coroutine returns a yield instruction  
  94.             yield return new WaitForSeconds(0.1f);  
  95.         }  
  96.     }  
  97.    
  98. }  

 上面的代碼實現是兩個協程交替調用,對有這種需求來講實在太精妙了。

 

 

小結:

        今天仔細看了下UnityGems.com 有關Coroutine的兩篇文章,雖然第一篇(參考①)如今驗證的結果有不少錯誤,但對於理解協程仍是不錯的,尤爲是當我發現Hijack這個腳本時,就火燒眉毛分享給你們。

   

        原本沒以爲會有UnityGems.com上的文章會有錯誤的,無心測試了發現仍是有很大的出入,固然這也不是說原來做者沒有通過驗證就妄加揣測,D.S.Qiu以爲頗有多是Unity內部的實現機制改變了,這種東西徹底能夠改動,Unity雖然開發了不少年了,可是其實在實際開發中仍是有不少坑,愈加以爲Unity的無力,雖然說容易上手,可是填坑的功夫也是必不可少的。      

       

        看來不少結論仍是要經過本身的驗證才行,貿然複製粘貼很難出真知,切記!

 

        若是您對D.S.Qiu有任何建議或意見能夠在文章後面評論,或者發郵件(gd.s.qiu@gmail.com)交流,您的鼓勵和支持是我前進的動力,但願能有更多更好的分享。

        轉載請在文首註明出處:http://dsqiu.iteye.com/blog/2029701

更多精彩請關注D.S.Qiu的博客和微博(ID:靜水逐風)    

 

參考:

①UnityGems.com: http://unitygems.com/coroutines/

②UnityGems.com: http://unitygems.com/advanced-coroutines/

蔥燒烙餅: http://blog.sina.com.cn/s/blog_5b6cb9500100xgmp.html

相關文章
相關標籤/搜索