免费国产网站_秋霞午夜一区二区三区视频_99热在线看_日韩精品久久一区二区_午夜看一级毛片_天天鲁在视频在线观看

  • Unity3D協(xié)程Coroutine解析

    2019/1/9??????點(diǎn)擊:

    本文只是從Unity的角度去分析理解協(xié)程的內(nèi)部運(yùn)行原理,而不是從C#底層的語法實(shí)現(xiàn)來介紹(后續(xù)有需要再進(jìn)行介紹),一共分為三部分:

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

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

    2. Unity中協(xié)程的執(zhí)行原理

    UnityGems.com給出了協(xié)程的定義: 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. 即協(xié)程是一個(gè)分部執(zhí)行,遇到條件(yield return 語句)會(huì)掛起,直到條件滿足才會(huì)被喚醒繼續(xù)執(zhí)行后面的代碼。 Unity在每一幀(Frame)都會(huì)去處理對(duì)象上的協(xié)程。Unity主要是在Update后去處理協(xié)程(檢查協(xié)程的條件是否滿足),但也有寫特例: 從上圖的剖析就明白,協(xié)程跟Update()其實(shí)一樣的,都是Unity每幀對(duì)會(huì)去處理的函數(shù)(如果有的話)。如果MonoBehaviour 是處于激活(active)狀態(tài)的而且yield的條件滿足,就會(huì)協(xié)程方法的后面代碼。還可以發(fā)現(xiàn):如果在一個(gè)對(duì)象的前期調(diào)用協(xié)程,協(xié)程會(huì)立即運(yùn)行到第一個(gè) yield return 語句處,如果是 yield return null ,就會(huì)在同一幀再次被喚醒。如果沒有考慮這個(gè)細(xì)節(jié)就會(huì)出現(xiàn)一些奇怪的問題『1』。 『1』注 圖和結(jié)論都是從UnityGems.com 上得來的,經(jīng)過下面的驗(yàn)證發(fā)現(xiàn)與實(shí)際不符,D.S.Qiu用的是Unity 4.3.4f1 進(jìn)行測試的。 經(jīng)過測試驗(yàn)證,協(xié)程至少是每幀的LateUpdate()后去運(yùn)行。

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

    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");
        }
    }
    得到日志輸入結(jié)果如下:



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

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

    經(jīng)過驗(yàn)證,『2』的結(jié)論也是錯(cuò)誤的,正確的結(jié)論是,MonoBehaviour.enabled = false 協(xié)程會(huì)照常運(yùn)行,但 gameObject.SetActive(false) 后協(xié)程卻全部停止,即使在Inspector把 gameObject 激活還是沒有繼續(xù)執(zhí)行:

    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中調(diào)用 this.enabled = false; 得到的結(jié)果:



    然后把 this.enabled = false; 注釋掉,換成 this.gameObject.SetActive(false); 得到的結(jié)果如下:

    整理得到 :通過設(shè)置MonoBehaviour腳本的enabled對(duì)協(xié)程是沒有影響的,但如果 gameObject.SetActive(false) 則已經(jīng)啟動(dòng)的協(xié)程則完全停止了,即使在Inspector把gameObject 激活還是沒有繼續(xù)執(zhí)行。也就說協(xié)程雖然是在MonoBehvaviour啟動(dòng)的(StartCoroutine)但是協(xié)程函數(shù)的地位完全是跟MonoBehaviour是一個(gè)層次的,不受MonoBehaviour的狀態(tài)影響,但跟MonoBehaviour腳本一樣受gameObject 控制,也應(yīng)該是和MonoBehaviour腳本一樣每幀“輪詢” yield 的條件是否滿足。


    yield 后面可以有的表達(dá)式:

    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影響,當(dāng)Time.timeScale = 0f 時(shí),yield return new WaitForSecond(x) 將不會(huì)滿足。

    3. IEnumerator & Coroutine

    協(xié)程其實(shí)就是一個(gè)IEnumerator(迭代器),IEnumerator 接口有兩個(gè)方法 Current 和 MoveNext() ,前面介紹的TaskManager就是利用者兩個(gè)方法對(duì)協(xié)程進(jìn)行了管理,這里在介紹一個(gè)協(xié)程的交叉調(diào)用類 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);
            }
        }
    }
    上面的代碼實(shí)現(xiàn)是兩個(gè)協(xié)程交替調(diào)用。



    主站蜘蛛池模板: 图片区小说区AV区_av在线高清观看_中国一级毛片免费高清_九九精品在线观看视频_日韩国产精_777婷婷天堂综合区色吧 | 无码吃奶揉捏奶头高潮视频_新白娘子传奇50集免费看高清_99久久er这里只有精品18_少妇人妻200篇白洁_欧美aaaa视频_欧美成人午夜剧场 | 97色在线观看免费视频_岛国岛国免费v片在线观看_日韩综合一区二区_九一视频在线免费观看_久久精品国产露脸对白_日韩999 | 欧美精品1_国产酒店强推在线观看_日韩性生活大片_靠逼网站在线观看_亚洲国产精品一区_国产精品色欲AV亚洲三区 | 亚洲国产精品自在拍在线播放蜜臀_日本高清hd在线播放_欧美老妇人XXXX_久久二三区_26uuu国产亚洲精品_亚洲综合精品一区二区 | 精品久久二区_免费女上男下xx00xx00视频_日韩精品无码中文字幕一区二区_在线成人免费观看_国内伊人久久久久久网站视频_a级毛片三个男人一女 | 毛片毛片_18成年片免费视频网站_国内精品国产三级国产AV_久久成人激情_久草三级_搞逼视频免费 | 国产毛片一区二区精品_在线天堂资源WWW在线污_亚洲成aⅴ人片_人妻无码中文专区久久五月婷_成人久久久_mimiaiboard最新地址 | 有坂深雪av一区二区精品_亚洲欧洲日韩一区_成人免费高清视频_亚洲特黄一级_欧美久久久精品_亚洲AV成人一二三区观看 | 国产一区精选播放022_成年人高清视频在线观看_把腿张开抹春药调教男男_亚洲精品AA片在线观看国产_91社区影院_露脸国产精品自产拍在线观看 | 欧美成网站_日韩福利视频在线_图片小说校园激情都市_毛片免费看看_777久久_国产精品无码欧美日韩 | 91凹凸国产分类在线观看_亚洲午夜av久久乱码_中文在线亚洲_国产乱码精品一区二区三区不卡_国产一级成人_18亚洲gay男男1069 | 91成人免费视频观看_色综合99久久久无码国产精品_天天宗合网_全亚洲第一av番号网站_久久午夜无码鲁丝片午夜精品_国产男女爱猛视频在线 | 亚洲极美女高清视频_日日夜夜成人_一级日韩_播放毛片_AV一本久道久久波多野结衣_欧美成人三区 | 国产精品成人观看视频国产奇米_欧美日韩中文视频_五月丁香五月伦理_亚洲国产精品成人综合久久久久久久_69式高清视频在线观看_四虎com | 777午夜_女调教脚奴网站_亚洲精品~无码抽插_两个黑人大战嫩白金发美女_两个奶头被吃高潮_久久久国产精品免费a片3d | 日韩欧美精品一区二区_国产精品视频资源_伊人久久综合热线大杳蕉_18禁成人无遮羞网站免费_亚洲AV无码AV在线影院_丰满熟妇另类激情 | 熟女系列丰满熟妇AV_免费观看黄视频_久久99性xxx老妇胖精品_国产一区在线观看麻豆_特级做爰图片_日本高清色视频在线播放 | 亚洲毛片av_99热精品国产麻豆_一区二区丝袜_精品91av_天堂网www在线资源链接_麻豆精品视频 | 97AV麻豆蜜桃一区二区_黄色一级片av_日本视频中文字幕一区二区三区_91精品一区二区三区久久久久久_操人视频在线免费观看_男女啪啪高潮无遮挡免费 | 免费观看视频91_久久91热_www.麻豆传媒_国产剧情资源在线视频_午夜毛片网_成全高清免费观看MV动漫 | 好紧好湿好硬国产在线视频_亚洲AV无码一区二区三区人_看视频免费网址_久久久久网站_极品美女大尺度私房写真_福利一区二区三区视频在线观看 | caopom在线视频免费观看_av免费播放_成年免费A级毛片免费看无码_一卡2卡3卡四卡精品免费网站_草莓香蕉樱桃黄瓜视频_91黄色看片 | 日本搞黄_精品国产偷窥一区二区_久久中文一区_久久1区2区3区_男女无遮挡高清性视频_成人av在线网址 | av青草_成人免费视频_色狠狠AV一区二区三区_无码av无码天堂资源网影音先锋_国产精品一区二区不卡_男人J桶女人P免费视频 | 成人国产区_大狠狠大臿蕉香蕉大视频_99久久久无码国产精品_野狼AV午夜福利在线_亚洲色图一区二区三区_色激情五月 | 成人黄色三级毛片_亚洲福利免费_在线另类播放_黄色的视频在线观看_国产一区二区91_国产毛片精品一区二区 | 日本黄色片一区_韩国三级高潮爽_天堂亚洲免费视频_久热精品在线视频_操操操综合网_国产999视频在线播放 | 99视频在线免费播放_午夜a级理论片在线播放717_色网站视频在线观看_超碰在线免费观看97_亚洲男人天堂网_狠狠网站 | 男人女人努力生猴子_精品国产乱码一区二区三区四区_中文字幕在线一_国产精品免费观看久久_国产黄色大片网站_在线免费av片 | 91视频在线观看大全_亚洲狠狠狠_亚洲777理论_久久精品国产亚洲AV麻豆网站_精品国产乱码久久久久久1区2区_国产女爽爽视频精品免费 | 久久影院综合精品_小明看欧美日韩免费视频_www.88av.com最新网址_女上位av片在线观看免费_极品色av影院_亚洲人天堂 | 国产伦高清一区二区三区_四虎4hutv紧急入口_国产片av_99久久精品免费_日本va中文字幕_日韩久久久 | 91精品91久久久久久_a在线一区_性迷宫在线播放_欧美在线视频一二三区_久久99精品国产自在现线_久久精品超碰 | 人人妻人人做人人爽夜欢视频_在线观看中文资源视频_男人的网站在线观看_亚洲综合久久久久_日本hd好看的国产的_欧美一区二区免费 | 午夜毛片免费_无码一区二区三区爆白浆_成人区人妻精品一区二区不卡网站_69大片视频免费观看视频_91亚洲精品_亚洲一级毛片免费在线观看 | 亚洲天堂色网站_欧美牲交videossexeso_亚洲精品人成_亚洲欧美网址_国产一级淫片免费看_国产精品久久久久久久一区二区 | 日本午夜片无码区在线观看_日韩欧美视频网站_中文在线a天堂_朝桐光一区_日韩免费av网站_先锋av资源 | 黑人一级毛片_对白离婚国产乱子伦视频大全_婷婷天堂网_japanesehdxxxx乳_亚洲精品免费视频_h片在线 | 老熟妇hdxxx_国产5页_用舌头去添高潮无码AV在线观看_大西瓜av_国产日韩AV免费无码一区二区_亚洲尺码日本尺码专线 | 安眠药扒开女同学双腿玩弄_久久久久人妻精品一区三寸_亚洲老逼_欧美精品日本_成人av天堂_色综合免费 |