IEnumerator/ IEnumerable/ yield return详解

发表于2017-09-11
评论0 3.3k浏览

Update逻辑




IEnumerator/ IEnumerable

  1. public interface IEnumerable    
  2. {    
  3.     IEnumerator GetEnumerator();    
  4. }    
  5.      
  6. public interface IEnumerator    
  7. {    
  8.     bool MoveNext();    
  9.     void Reset();    
  10.      
  11.     Object Current { get; }    
  12. }    

在两者的使用上,有下面几点需要注意

1、一个Collection要支持foreach方式的遍历,必须实现IEnumerable接口(亦即,必须以某种方式返回IEnumerator object)。
2、IEnumerator object具体实现了iterator(通过MoveNext(),Reset(),Current)。
3、从这两个接口的用词选择上,也可以看出其不同:IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumerator object就是一个iterator。
4、IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接,client可以通过IEnumerable的GetEnumerator()得到IEnumerator object,在这个意义上,将GetEnumerator()看作IEnumerator object的factory method也未尝不可。


yield return

使用yield语句可以暂停(pause)协同程序的执行,yield的返回值指定在什么时候继续(resume)协同程序。

yield return null; //暂停协同程序,下一帧再继续往下执行
yield new WaitForFixedUpdate (); //暂停协同程序,等到下一次调用FixedUpdate方法时再继续往下执行
yield return new WaitForSeconds(2);//暂停协同程序,2秒之后再继续往下执行
yield return StartCoroutine("SomeCortoutineMethod");//暂停此协同程序,开启SomeCortoutineMethod协同程序,直到SomeCortoutineMethod里的内容全部搞定。



StartCoroutine

在Unity3D中,使用MonoBehaviour.StartCoroutine方法即可开启一个协同程序,也就是说该方法必须在MonoBehaviour或继承于MonoBehaviour的类中调用。

在Unity3D中,使用StartCoroutine(string methodName)和StartCoroutine(IEnumerator routine)都可以开启一个线程。区别在于使用字符串作为参数可以开启线程并在线程结束前终止线程,相反使用IEnumerator 作为参数只能等待线程的结束而不能随时终止(除非使用StopAllCoroutines()方法);另外使用字符串作为参数时,开启线程时最多只能传递 一个参数,并且性能消耗会更大一点,而使用IEnumerator 作为参数则没有这个限制。

在Unity3D中,使用StopCoroutine(string methodName)来终止一个协同程序,使用StopAllCoroutines()来终止所有可以终止的协同程序,但这两个方法都只能终止该 MonoBehaviour中的协同程序。

还有一种方法可以终止协同程序,即将协同程序所在gameobject的active属性设置为false,当再次设置active为ture时,协同程 序并不会再开启;如是将协同程序所在脚本的enabled设置为false则不会生效。这是因为协同程序被开启后作为一个线程在运行,而 MonoBehaviour也是一个线程,他们成为互不干扰的模块,除非代码中用调用,他们共同作用于同一个对象,只有当对象不可见才能同时终止这两个线 程。然而,为了管理我们额外开启的线程,Unity3D将协同程序的调用放在了MonoBehaviour中,这样我们在编程时就可以方便的调用指定脚本 中的协同程序,而不是无法去管理,特别是对于只根据方法名来判断线程的方式在多人开发中很容易出错,这样的设计保证了对象、脚本的条理化管理,并防止了重 名。


示例1

  1. public class GameManager : MonoBehaviour {  
  2.   
  3.      void Start()   
  4.     {   
  5.        Debug.Log("Starting "   Time.time);  
  6.         StartCoroutine(WaitAndPrint(2));  
  7.         Debug.Log("Done "   Time.time);  
  8.     }  
  9.   
  10.     IEnumerator WaitAndPrint(float waitTime)   
  11.     {   
  12.         yield return new WaitForSeconds(waitTime);   
  13.         Debug.Log("WaitAndPrint "   Time.time);  
  14.     }  
  15. }  


运行结果:



  1. public class GameManager : MonoBehaviour {  
  2.   
  3.     IEnumerator Start()   
  4.     {  
  5.         Debug.Log("Starting "   Time.time);  
  6.         yield return StartCoroutine(WaitAndPrint(2.0F));  
  7.         Debug.Log("Done "   Time.time);  
  8.     }  
  9.     IEnumerator WaitAndPrint(float waitTime)   
  10.     {   
  11.         yield return new WaitForSeconds(waitTime);  
  12.         Debug.Log("WaitAndPrint "   Time.time);  
  13.     }   
  14. }  

运行结果:



再看一个yield return StartCoroutine嵌套的例子
  1. void Start () {  
  2.        Debug.Log("start1");  
  3.        StartCoroutine(Test());  
  4.        Debug.Log("start2");  
  5.    }  
  6.   
  7.    IEnumerator Test()  
  8.    {  
  9.        Debug.Log("test1");  
  10.        yield return StartCoroutine(DoSomething());  
  11.        Debug.Log("test2");  
  12.    }  
  13.   
  14.    IEnumerator DoSomething()  
  15.    {  
  16.        Debug.Log("load 1");  
  17.        yield return null;  
  18.        Debug.Log("load 2");  
  19.    }  


执行结果:

start1

test1

load1

start2

load2

test2

这种StartCoroutine中嵌套一个yield return StartCoroutine,第一个StartCoroutine会等到第二个StartCoroutine中所有代码结束后再继续执行,而第二个StartCoroutine中的yield语句会先返回第一个,然后立即返回他的调用处,也就是调用处会继续执行,而第一个StartCoroutine会等待第二个执行完再继续执行。


示例二

场景如下,一个球一个平面。



球的控制器

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class SphereController : MonoBehaviour {  
  5.     private Vector3 target;  
  6.     public float smoothing = 7f;  
  7.   
  8.     public Vector3 Target  
  9.     {  
  10.         get { return target; }  
  11.         set  
  12.         {  
  13.             target = value;  
  14.   
  15.             StopCoroutine("Movement");  
  16.             StartCoroutine("Movement", target);  
  17.             Debug.Log("Move!");  
  18.         }  
  19.     }  
  20.   
  21.     IEnumerator Movement(Vector3 target)  
  22.     {  
  23.         while(Vector3.Distance(transform.position, target) > 0.05f)  
  24.         {  
  25.             transform.position = Vector3.Lerp(transform.position, target, smoothing * Time.deltaTime);  
  26.             yield return null;  
  27.         }  
  28.     }  
  29.   
  30. }  

下面的脚本拖拽到地面上
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class ClickSetPosition : MonoBehaviour {  
  5.     public SphereController sphereController;  
  6.     // Update is called once per frame  
  7.     void Update()  
  8.     {  
  9.         if (Input.GetMouseButtonDown(0))  
  10.         {  
  11.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
  12.             RaycastHit hit;  
  13.   
  14.             Physics.Raycast(ray, out hit);  
  15.   
  16.             if (hit.collider.gameObject == gameObject)  
  17.             {  
  18.                 Debug.Log("Clicked!");  
  19.                 Vector3 newTarget = hit.point   new Vector3(0, 0.5f, 0);  
  20.                 sphereController.Target = newTarget;  
  21.             }  
  22.         }  
  23.     }  
  24. }  

运行结果


如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签: