Unity日记22(携程概念)
目录
学习视频
1异步
2调用方法
3优点
4停止方法
5返回值
实例:每过一秒打印当前运行时间
实例:停止数字打印携程
错误方法:(携程只能开一个)
参考方法
学习视频
https://www.bilibili.com/video/BV1eu411U7EL/?spm_id_from=333.337.search-card.all.click&vd_source=ab35b4ab4f3968642ce6c3f773f85138
携程
是一个返回值是IEnumerator的函数,异是一个步多任务处理的函数
异步
异步多任务处理:穿插处理任务
异步意味着不停止就会运行。
调用方法
startcoroutine(方法)
startcoroutine(方法名)
优点
代替update的方法:update方法,每帧执行一次,非常消耗内存。
停止方法
StopCoroutine(方法名)
StopAllCoroutines()
返回值
实例:每过一秒打印当前运行时间
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IEnumer : MonoBehaviour
{void Start(){StartCoroutine(Timer());}IEnumerator Timer(){int count = 0;while (true){yield return new WaitForSeconds(1);count++;Debug.Log(count);}}
}
实例:停止数字打印携程
判断成功标准:不再打印数字
错误方法:(携程只能开一个)
Func_Controller没把Timer停下来
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IEnumer : MonoBehaviour
{int count = 0;void Start(){StartCoroutine(Timer());StopCoroutine(Func_Controller());//5秒后停止指定携程}IEnumerator Timer(){while (true){yield return new WaitForSeconds(1);count++;Debug.Log(count);}}IEnumerator Func_Controller(){if (count >= 5){StopCoroutine(Timer());Debug.Log("STOP");yield return 1;}}
}
参考方法
在TImer里面写,在同一个携程内实现停止自身。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class IEnumer : MonoBehaviour
{int count = 0;void Start(){StartCoroutine(Timer());}IEnumerator Timer(){while (true){yield return new WaitForSeconds(1);//等一秒count++;Debug.Log(count);if (count >= 5){StopCoroutine(Timer());Debug.Log("STOP");yield break;}}}
}