最新国产在线视频_一色一伦一区二区三区的区别_欧美成人影院亚洲综合图_国产亚洲一区精品_大胆欧美熟妇xxbbwwbw高潮了_久久午夜无码鲁丝片

  • 您的位置:首頁 > 新聞動態 > Unity3D

    Unity3D協程Coroutine解析

    2019/1/9??????點擊:

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

    1. 線程(Thread)和協程(Coroutine)

    使用協程的作用一共有兩點:1)延時(等待)一段時間執行代碼;2)等某個操作完成之后再執行后面的代碼。總結起來就是一句話:控制代碼在特定的時機執行。 很多初學者,都會下意識地覺得協程是異步執行的,都會覺得協程是C# 線程的替代品,是Unity不使用線程的解決方案。 所以首先,請你牢記:協程不是線程,也不是異步執行的。協程和 MonoBehaviour 的 Update函數一樣也是在MainThread中執行的。使用協程你不用考慮同步和鎖的問題。

    2. 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 中分別進行測試:

    using UnityEngine;
    using System.Collections;
    
    public class TestCoroutine : MonoBehaviour {
    
        private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once
        private bool isUpdateCall = false;
        private bool isLateUpdateCall = false;
        // Use this for initialization
        void Start () {
            if (!isStartCall)
            {
                Debug.Log("Start Call Begin");
                StartCoroutine(StartCoutine());
                Debug.Log("Start Call End");
                isStartCall = true;
            }
    
        }
        IEnumerator StartCoutine()
        {
    
            Debug.Log("This is Start Coroutine Call Before");
            yield return null;
            Debug.Log("This is Start Coroutine Call After");
    
        }
        // Update is called once per frame
        void Update () {
            if (!isUpdateCall)
            {
                Debug.Log("Update Call Begin");
                StartCoroutine(UpdateCoutine());
                Debug.Log("Update Call End");
                isUpdateCall = true;
            }
        }
        IEnumerator UpdateCoutine()
        {
            Debug.Log("This is Update Coroutine Call Before");
            yield return null;
            Debug.Log("This is Update Coroutine Call After");
        }
        void LateUpdate()
        {
            if (!isLateUpdateCall)
            {
                Debug.Log("LateUpdate Call Begin");
                StartCoroutine(LateCoutine());
                Debug.Log("LateUpdate Call End");
                isLateUpdateCall = true;
            }
        }
        IEnumerator LateCoutine()
        {
            Debug.Log("This is Late Coroutine Call Before");
            yield return null;
            Debug.Log("This is Late Coroutine Call After");
        }
    }
    得到日志輸入結果如下:



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

    MonoBehaviour 沒有針對特定的協程提供Stop方法,其實不然,可以通過MonoBehaviour enabled = false 或者 gameObject.active = false 就可以停止協程的執行『2』。

    經過驗證,『2』的結論也是錯誤的,正確的結論是,MonoBehaviour.enabled = false 協程會照常運行,但 gameObject.SetActive(false) 后協程卻全部停止,即使在Inspector把 gameObject 激活還是沒有繼續執行:

    using UnityEngine;
    using System.Collections;
    
    public class TestCoroutine : MonoBehaviour {
    
      private bool isStartCall = false;  //Makesure Update() and LateUpdate() Log only once
      private bool isUpdateCall = false;
      private bool isLateUpdateCall = false;
      // Use this for initialization
      void Start () {
        if (!isStartCall)
        {
          Debug.Log("Start Call Begin");
          StartCoroutine(StartCoutine());
          Debug.Log("Start Call End");
          isStartCall = true;
        }
    
      }
      IEnumerator StartCoutine()
      {
    
        Debug.Log("This is Start Coroutine Call Before");
        yield return new WaitForSeconds(1f);
        Debug.Log("This is Start Coroutine Call After");
    
      }
      // Update is called once per frame
      void Update () {
        if (!isUpdateCall)
        {
          Debug.Log("Update Call Begin");
          StartCoroutine(UpdateCoutine());
          Debug.Log("Update Call End");
          isUpdateCall = true;
          this.enabled = false;
          //this.gameObject.SetActive(false);
        }
      }
      IEnumerator UpdateCoutine()
      {
        Debug.Log("This is Update Coroutine Call Before");
        yield return new WaitForSeconds(1f);
        Debug.Log("This is Update Coroutine Call After");
        yield return new WaitForSeconds(1f);
        Debug.Log("This is Update Coroutine Call Second");
      }
      void LateUpdate()
      {
        if (!isLateUpdateCall)
        {
          Debug.Log("LateUpdate Call Begin");
          StartCoroutine(LateCoutine());
          Debug.Log("LateUpdate Call End");
          isLateUpdateCall = true;
    
        }
      }
      IEnumerator LateCoutine()
      {
        Debug.Log("This is Late Coroutine Call Before");
        yield return null;
        Debug.Log("This is Late Coroutine Call After");
      }
    }
    先在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) 將不會滿足。

    3. IEnumerator & Coroutine

    協程其實就是一個IEnumerator(迭代器),IEnumerator 接口有兩個方法 Current 和 MoveNext() ,前面介紹的TaskManager就是利用者兩個方法對協程進行了管理,這里在介紹一個協程的交叉調用類 Hijack:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    [RequireComponent(typeof(Text))]
    public class HiJack : MonoBehaviour {
    
        //This will hold the counting up coroutine
        IEnumerator _countUp;
        //This will hold the counting down coroutine
        IEnumerator _countDown;
        //This is the coroutine we are currently
        //hijacking
        IEnumerator _current;
    
        //A value that will be updated by the coroutine
        //that is currently running
        int value = 0;
    
        void Start()
        {
            //Create our count up coroutine
            _countUp = CountUp();
            //Create our count down coroutine
            _countDown = CountDown();
            //Start our own coroutine for the hijack
            StartCoroutine(DoHijack());
        }
    
        void Update()
        {
            //Show the current value on the screen
            GetComponent().text = value.ToString ();
        }
    
        void OnGUI()
        {
            //Switch between the different functions
            if(GUILayout.Button("Switch functions"))
            {
                if(_current == _countUp)
                    _current = _countDown;
                else
                    _current = _countUp;
            }
        }
    
        IEnumerator DoHijack()
        {
            while(true)
            {
                //Check if we have a current coroutine and MoveNext on it if we do
                if(_current != null && _current.MoveNext())
                {
                    //Return whatever the coroutine yielded, so we will yield the
                    //same thing
                    yield return _current.Current;
                }
                else
                    //Otherwise wait for the next frame
                    yield return null;
            }
        }
    
        IEnumerator CountUp()
        {
            //We have a local increment so the routines
            //get independently faster depending on how
            //long they have been active
            float increment = 0;
            while(true)
            {
                //Exit if the Q button is pressed
                if(Input.GetKey(KeyCode.Q))
                    break;
                increment+=Time.deltaTime;
                value += Mathf.RoundToInt(increment);
                yield return null;
            }
        }
    
        IEnumerator CountDown()
        {
            float increment = 0f;
            while(true)
            {
                if(Input.GetKey(KeyCode.Q))
                    break;
                increment+=Time.deltaTime;
                value -= Mathf.RoundToInt(increment);
                //This coroutine returns a yield instruction
                yield return new WaitForSeconds(0.1f);
            }
        }
    }
    上面的代碼實現是兩個協程交替調用。



    主站蜘蛛池模板: 亚洲日日摸夜夜夜夜夜爽小说 | 亚洲天堂男人 | 成人黄色国产 | 亚洲成人一区二区三区 | 国产一级久久久久 | 狠狠色成人一区二区三区 | 欧美性生交XXXXX无码小说 | 在线播放heyzo无码 | 亚洲av日韩av天堂久久 | 麻豆免费版在线观看 | 伊人国产精品 | 俺来也最新地址 | 亚洲最大在线视频 | 日本午夜片 | 久久国产精品人妻无码 | 九月婷婷综合 | 中国国产av片 | 少妇爱做高清免费视频 | 亚洲AV色男人的天堂在线观看 | 好男人社区WWW在线观看 | 偷自拍亚洲视频在线观看99 | 绿帽在线 | 精品视频国产一区 | 猫咪WWW免费人成网站 | 麻豆蜜桃AV蜜臀AV色欲AV | 国产精品女上位 | www亚洲com| 调教小公主高潮h失禁视频 少妇av射精精品蜜桃专区 | 欧美又大又粗AAA片免费看 | 一区二区三区四区在线播放 | 亚洲国产欧美国产第一区 | 俺要去97中文字幕 | 噜噜噜视频 | 欧美三级不卡在线观线看 | 日本精品久久久久中文字幕乱中年 | 韩国久久久久久 | 亚洲精品av久久久久久久影院 | 扒开女人内裤猛进猛出免费视频 | 欧美亚洲国产精品久久高清 | 成人亚洲性情网站www在线观看 | 99久久精品69堂 |