找回密码
 立即注册
查看: 618|回复: 1

[笔记] Unity协程(Coroutine)原理深入剖析

[复制链接]
发表于 2021-2-20 16:37 | 显示全部楼层 |阅读模式
https://m.ke.qq.com/course/2349966?flowToken=1022178 (二维码自动识别)
原文转载于:Unity协程(Coroutine)原理深入剖析 - One thing I know,that is I know nothing.(Socrates Greek) - ITeye博客
线程(Thread)和协程(Coroutine)  
        D.S.Qiu觉得使用协程的作用一共有两点:1)延时(等待)一段时间执行代码;2)等某个操作完成之后再执行后面的代码。总结起来就是一句话:控制代码在特定的时机执行。
        很多初学者,都会下意识地觉得协程是异步执行的,都会觉得协程是C# 线程的替代品,是Unity不使用线程的解决方案。
        所以首先,请你牢记:协程不是线程,也不是异步执行的。协程和 MonoBehaviour 的 Update函数一样也是在MainThread中执行的。使用协程你不用考虑同步和锁的问题。
Unity中协程的执行原理
        http://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』注 图和结论都是从http://UnityGems.com 上得来的,经过下面的验证发现与实际不符,D.S.Qiu用的是Unity 4.3.4f1 进行测试的。经过测试验证,协程至少是每帧的LateUpdate()后去运行。
        下面使用 yield return new WaitForSeconds(1f); 在Start,Update 和 LateUpdate 中分别进行测试:
  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; 发现日志输入结果和上面是一样的,没有出现上面说的情况:
  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 Stat 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之后,下面附上:』
前面在介绍TaskManager工具时,说到MonoBehaviour 没有针对特定的协程提供Stop方法,其实不然,可以通过MonoBehaviour enabled = false 或者 gameObject.active = false 就可以停止协程的执行『2』。
        经过验证,『2』的结论也是错误的,正确的结论是,MonoBehaviour.enabled = false 协程会照常运行,但 gameObject.SetActive(false) 后协程却全部停止,即使在Inspector把  gameObject 激活还是没有继续执行:
  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(参见附件):
  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. }  
复制代码
上面的代码实现是两个协程交替调用,对有这种需求来说实在太精妙了。
小结:
        今天仔细看了下http://UnityGems.com 有关Coroutine的两篇文章,虽然第一篇(参考①)现在验证的结果有很多错误,但对于理解协程还是不错的,尤其是当我发现Hijack这个脚本时,就迫不及待分享给大家。
        本来没觉得会有http://UnityGems.com上的文章会有错误的,无意测试了发现还是有很大的出入,当然这也不是说原来作者没有经过验证就妄加揣测,D.S.Qiu觉得很有可能是Unity内部的实现机制改变了,这种东西完全可以改动,Unity虽然开发了很多年了,但是其实在实际开发中还是有很多坑,越发觉得Unity的无力,虽说容易上手,但是填坑的功夫也是必不可少的。      
        看来很多结论还是要通过自己的验证才行,贸然复制粘贴很难出真知,切记!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
发表于 2021-2-20 16:43 | 显示全部楼层
写的非常清楚,经过unity5和最新官网流程图,代码验证,如果是 yield return null ,就会在下一帧再次被唤醒。且执行流程为在Update之后,LateUpdate之前。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-4 14:14 , Processed in 0.314755 second(s), 27 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表