理解协程
IEnumerator+yield 强大的迭代器
IEnumerator 就是一个函数容器 里面保存了一个一个的函数
IEnumator会依次执行每个函数 而每个函数都有一个返回值 保存在IEnumator.Currect里面
看下面这个例子
IEnuermator start_Coroutine(){Debug.Log("HellWord");yield return 1;Debug.Log("HellWod!!!");yield return "abc";
}yield就是从开始到yield之间的代码做成一个函数 实际上可以理解为yield就是如下
function (){Debug.Log("HellWord");return 1;
}
function (){Debug.Log("HellWord!!!");return "abc";
}启动协程 this.StartCoroutine(e);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IECoroutine : MonoBehaviour
{void Start(){IEnumerator e = this.start_Coroutine();this.StartCoroutine(e);}IEnumerator start_Coroutine(){Debug.Log("HellWord");yield return 1;Debug.Log("HellWod!!!");yield return "abc";}
}
yield return null;11下一帧再执行后续代码
yield return 0;1/下一帧再执行后续代码
vield return 6:/1任意数字)下一帧再执行后续代码
vield break;1/直接结束该协程的后续操作
yield return asyncOperation://等异步操作结束后再执行后续代码
vield return StartCoroution(/*某个协程*八://等待某个协程执行完毕后再执行后续代码
yield return www0://等待www操作完成后再执行后续代码
vield return new WaitForEndOfFrame()://等待帧结束,等待直到所有的摄像机和GU被渲染完成后,在该帧显示在屏幕之前执行
yield return new WaitForseconds(0.3f)://等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的
间会受到Time.timescale的影响)
vield return new WaitForSecondsRealtime(0.3f)://等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后
(这里的时间不受到Time.timescale的影响);
yield return WaitForFixedUpdate()://等待下一次Fixedupdate开始时再执行后续代码
vield return new WaitUntil0//将协同执行直到 当输入的参数(或者委托)为true的时候
yield return new Waitwhile0//将协同执行直到 当输入的参数(或者委托)为false的时候
模拟协程实现过程
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IECoroutine : MonoBehaviour
{IEnumerator ie = null;void Start(){ie = this.start_Coroutine();}IEnumerator start_Coroutine(){Debug.Log("HellWord");yield return 1;Debug.Log("HellWod!!!");yield return "abc";}void LateUpdate(){if (this.ie != null){if (!this.ie.MoveNext()){this.ie = null;}else{Debug.Log("ie.Current = " + ie.Current);}}}
}
输出结果如下

IEnumerator.MoveNext:执行当前函数 并将返回值存储到IEnumerator.Current里面 并把函数索引拨动到下一个 如果执行到头了 没有可执行的函数了 IEnumerator.MoveNext就会返回false
模拟协程等待时间
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IECoroutine : MonoBehaviour
{IEnumerator ie = null;void Start(){ie = this.start_Coroutine();}IEnumerator start_Coroutine(){Debug.Log("HellWord");yield return 1;Debug.Log("HellWod!!!");yield return "abc";Debug.Log("开始等待3秒");yield return new ClassWaitForTime(3);Debug.Log("等待3秒结束");}void LateUpdate(){if (this.ie != null){if (this.ie.Current is ClassWaitForTime){ClassWaitForTime cw = ie.Current as ClassWaitForTime;cw.Update(Time.deltaTime);if (!cw.IsOver()){//时间未到则停止往下继续执行return;}}if (!this.ie.MoveNext()){this.ie = null;}else{Debug.Log("ie.Current = " + ie.Current);}}}
}class ClassWaitForTime
{private float total;private float nowtime;public ClassWaitForTime(float time){this.total = time;this.nowtime = 0;}public void Update(float time){this.nowtime += time;}public bool IsOver(){return this.nowtime >= this.total;}
}输出结果如下



















