1.什么是协程
协程实际上就是一个迭代器(IEnumerator),内部可以定义一些Yield Return挂起函数,判断协程函数内部执行的逻辑(通过Yield Return 延时,跳帧,等待下载或加载等操作将函数进行分步操作)
协程是基于生命周期的(下面会将执行顺序),是同步的,不是异步的(同一时间只会执行一个协程)
协程函数会被编译成一个状态机,每个状态都会关联下一个状态直至下一个为空
2.协程的使用
public class Test : MonoBehaviour
{
public void Start()
{
//开启协程
Coroutine testCoroutine = StartCoroutine(Test1());
//停止指定协程
StopCoroutine(testCoroutine);
//协程可以同时开启多个
StartCoroutine("Test1");
//StopCoroutine("Test1")只能停止StartCoroutine("Test1")开启的协程,对StartCoroutine(Test())开启的协程无效
StopCoroutine("Test");
//停止本脚本内所有协程
StopAllCoroutines();
}
IEnumerator Test1()
{
//等待下一帧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(Test1());
//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;
}
}