【轉】【UNITY3D 遊戲開發之六】UNITY 協程COROUTINE與INVOKE

本站文章均爲 李華明Himi 原創,轉載務必在明顯處註明:(作者新浪微博: @李華明Himi 
轉載自【黑米GameDev街區】 原文鏈接: http://www.himigame.com/unity3d-game/1610.html
 

          ☞ 點擊訂閱 ☜
 本博客最新動態!及時將最新博文通知您!


                 
width="150" height="210" frameborder="0" scrolling="no" src="http://widget.weibo.com/relationship/bulkfollow.php?language=zh_cn&uids=1916000601&wide=1&color=FFFFFF,FFFFFF,0082CB,666666&showtitle=0&showinfo=1&sense=0&verified=1&count=1&refer=http%3A%2F%2Fwww.himigame.com%2Funity3d-game%2F1610.html&dpc=1" style="border-width: 0px; margin: 0px; padding: 0px; font-family: arial, helvetica, clean, sans-serif; font-size: 12px; line-height: 16.0029983520508px;">

這裏Himi強調一點:Unity裏面的協程並不是線程,協程是在unity主線程中運行的,每一幀中處理一次,而並不與主線程並行。這就意味着在協程之間並不存在着所謂線程間的同步和互斥問題,不會出現死鎖。一般來說,訪問同一個值也都是很安全的,用協程可以處理絕大多數的小問題,而且不用考慮複雜的線程間同步,還是很方便的。
要說協程的不足就是不能運用處理器的多核來提高處理性能,畢竟這個在運行時事實上是在一個線程中執行的。

【以下均爲轉載內容】

1.     Unity3D –MonoBehaviour類Invoke,Coroutine :  http://www.himigame.com/wp-admin/post-new.php

2.    Unity3D協程介紹 以及 使用 : http://blog.csdn.net/huang9012/article/details/38492937

3.  U3D 遊戲開發中的 yield協程與消息傳遞 : http://blog.csdn.net/huang9012/article/details/38492937

 

Invoke:

 

在Unity中,延時執行一段代碼或者一個方法或者幾個方法的情況非常普遍。

一般會用到Invoke和InvokeRepeating方法。顧名思義,第一個是執行一次,第二個是重複執行。

看下定義:

void Invoke(string methodName, float time);

第一個參數是方法名(注意是字符串形式),並不是更方便的委託。第二個是延時多少秒。只執行一次。

void InvokeRepeating(string methodName, float time, float repeatRate);

InvokeRepeating第二個參數是延時多少秒後開始,第三個參數是每次執行間隔的秒數。

你有沒有發現這兩個方法有個弊端,就是必須輸入方法名!也就是我說,如果我想延時執行某段代碼,必須把代碼放在某個方法裏,然後使用這Invoke或者InvokeRepeating方法來執行。

這樣對於上下文變量、屬性的引用就會尤爲不便,而且不能傳參數!!!尼瑪,要他還有何用?

我猜你一定用過這樣的方法。沒錯,“協同”,聽起來還挺高大上的名字啊。

用StartCoroutine來執行一個以IEnumerator爲返回值的方法,通常用於異步下載啊,等比較耗時又不能讓遊戲卡死的情況。

還有一個好的類WaitForSeconds,對,它就一個構造函數,用來延時的(延時………………比萬艾可好用?比希愛力好用?)。

好了不廢話了,以下是我自用的延時方法,放在一個類裏以靜態方法存在。可以在任何時候任何地方延時指定秒數的代碼。

using UnityEngine;

using System.Collections;

using System;

public class DelayToInvoke : MonoBehaviour

{

public static IEnumerator DelayToInvokeDo(Action action, float delaySeconds)

{

yield return new WaitForSeconds(delaySeconds);

action();

}

}

如何使用呢?

比如我點擊NGUI的一個Button,則

void OnClick()

{

StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>

{

Application.LoadLevel(“Option”);

}, 0.1f));

}

 

C#中Invoke 和 BeginInvoke 的區別 : http://blog.csdn.net/allenjy123/article/details/7232321

 

Coroutine:

 

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

 

記得去年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類時,頓時覺得十分精巧,眼前一亮,遂動了寫文分享之。

 

線程(Thread)和協程(Coroutine)

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

得到日誌輸入結果如下:

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

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

『今天意外發現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. public class TestCoroutine : MonoBehaviour {
  4.     private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once
  5.     private bool isUpdateCall = false;
  6.     private bool isLateUpdateCall = false;
  7.     // Use this for initialization
  8.     void Start () {
  9.         if (!isStartCall)
  10.         {
  11.             Debug.Log(“Start Call Begin”);
  12.             StartCoroutine(StartCoutine());
  13.             Debug.Log(“Start Call End”);
  14.             isStartCall = true;
  15.         }
  16.     }
  17.     IEnumerator StartCoutine()
  18.     {
  19.         Debug.Log(“This is Start Coroutine Call Before”);
  20.         yield return new WaitForSeconds(1f);
  21.         Debug.Log(“This is Start Coroutine Call After”);
  22.     }
  23.     // Update is called once per frame
  24.     void Update () {
  25.         if (!isUpdateCall)
  26.         {
  27.             Debug.Log(“Update Call Begin”);
  28.             StartCoroutine(UpdateCoutine());
  29.             Debug.Log(“Update Call End”);
  30.             isUpdateCall = true;
  31.             this.enabled = false;
  32.             //this.gameObject.SetActive(false);
  33.         }
  34.     }
  35.     IEnumerator UpdateCoutine()
  36.     {
  37.         Debug.Log(“This is Update Coroutine Call Before”);
  38.         yield return new WaitForSeconds(1f);
  39.         Debug.Log(“This is Update Coroutine Call After”);
  40.         yield return new WaitForSeconds(1f);
  41.         Debug.Log(“This is Update Coroutine Call Second”);
  42.     }
  43.     void LateUpdate()
  44.     {
  45.         if (!isLateUpdateCall)
  46.         {
  47.             Debug.Log(“LateUpdate Call Begin”);
  48.             StartCoroutine(LateCoutine());
  49.             Debug.Log(“LateUpdate Call End”);
  50.             isLateUpdateCall = true;
  51.         }
  52.     }
  53.     IEnumerator LateCoutine()
  54.     {
  55.         Debug.Log(“This is Late Coroutine Call Before”);
  56.         yield return null;
  57.         Debug.Log(“This is Late Coroutine Call After”);
  58.     }
  59. }

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

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

 

 

小結:

今天仔細看了下UnityGems.com 有關Coroutine的兩篇文章,雖然第一篇(參考①)現在驗證的結果有很多錯誤,但對於理解協程還是不錯的,尤其是當我發現Hijack這個腳本時,就迫不及待分享給大家。

 

本來沒覺得會有UnityGems.com上的文章會有錯誤的,無意測試了發現還是有很大的出入,當然這也不是說原來作者沒有經過驗證就妄加揣測,D.S.Qiu覺得很有可能是Unity內部的實現機制改變了,這種東西完全可以改動,Unity雖然開發了很多年了,但是其實在實際開發中還是有很多坑,越發覺得Unity的無力,雖說容易上手,但是填坑的功夫也是必不可少的。

 

看來很多結論還是要通過自己的驗證才行,貿然複製粘貼很難出真知,切記!

 

 

發佈了173 篇原創文章 · 獲贊 1404 · 訪問量 301萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章