在动态加载资源或创建对象的时候,由于数量较多,在同一帧完成大量计算可能造成程序卡顿现象,这里就要用到协程,将大量计算分散到多帧里面完成。或在程序执行到某一步,需要等待一段时间,然后在继续执行,也需要用到协程。还有其他一些情况下,充分利用协程,可以更好地实现功能。

分享一下个人对协程的一些使用理解:
public void Start() { //开启协程 Coroutine testCoroutine = StartCoroutine(Test());
//停止指定协程 StopCoroutine(testCoroutine); //协程可以同时开启多个 StartCoroutine("Test");
//经实测,StopCoroutine("Test")只能停止StartCoroutine("Test")开启的协程,对StartCoroutine(Test())开启的协程无效
StopCoroutine("Test"); //停止本脚本内所有协程 StopAllCoroutines(); } IEnumerator Test() {
//等待下一帧Update之后,继续执行后续代码 yield return null; //等待在所有相机和GUI渲染之后,直到帧结束,继续执行后续代码
yield return new WaitForEndOfFrame(); //等待下一个FixedUpdate之后,继续执行后续代码 yield
return new WaitForFixedUpdate(); //等待3秒之后,继续执行后续代码,使用缩放时间暂停协程执行达到给定的秒数 yield
return new WaitForSeconds(3.0f); //等待3秒之后,继续执行后续代码,使用未缩放的时间暂停协程执行达到给定的秒数 yield
return new WaitForSecondsRealtime(3.0f); //等待直到Func返回true,继续执行后续代码 //yield
return new WaitUntil(System.Func<bool>); yield return new WaitUntil(() =>
true); //等待直到Func返回false,继续执行后续代码 //yield return new
WaitWhile(System.Func<bool>); yield return new WaitWhile(() => false);
//等待新开启的协程完成后,继续执行后续代码,可以利用这一点,实现递归 yield return StartCoroutine(Test());
//for循环 for (int i = 0; i < 10; i++) { Debug.Log(i); yield return new
WaitForSeconds(1); } //while循环,while(true):如果循环体内有yield return···语句,不会因为死循环卡死
int j = 0; while (j < 10) { j++; Debug.Log(j); yield return new
WaitForSeconds(1); } //终止协程 yield break; }
再分享一位大大的翻译博文,关于同步等待、同步协程、异步协程、并行协程,图文说明非常清晰~

Unity内置协程 <http://www.manew.com/thread-102065-1-1.html> (
http://www.manew.com/thread-102065-1-1.html
<http://www.manew.com/thread-102065-1-1.html>)

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信