美文网首页
四、生命周期:2、协程详解

四、生命周期:2、协程详解

作者: GameObjectLgy | 来源:发表于2022-03-14 10:27 被阅读0次
1、协程常规使用方式
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);
            }

           //当这个新的Coroutine执行完毕后,才继承执行现有Coroutine
           yield return StartCoroutine("NewCoroutine");

            //终止协程
            yield break;
        }
2、协程嵌套协程测试
public class CoroutineTest : MonoBehaviour
{
    // 最终执行顺序 111=>333=>444=>222
    void Start()
    {
        StartCoroutine(CoroutineFirst());
    }

    private IEnumerator CoroutineFirst()
    {
        Debug.Log(111);
        yield return StartCoroutine(CoroutineSecond());
        Debug.Log(222);
    }

    private IEnumerator CoroutineSecond()
    {
        Debug.Log(3333);
        yield return new WaitForSeconds(1);
        Debug.Log(4444);
    }
}
3、协程实现返回值机制

协程可以传递参数进入,但是没有返回值功能,有时候不方便使用。
采用回调机制,可以方便把在协程里处理完的结果,反馈出来。

4、协程的启用与销毁机制
  • 禁用 MonoBehaviour 时,不会停止协程,仅在明确销毁 MonoBehaviour 时才会停止协程。
  • 可以使用 MonoBehaviour.StopCoroutine 和 MonoBehaviour.StopAllCoroutines 来停止协程。
  • 销毁 MonoBehaviour 时,也会停止协程。
  • MonoBehaviour所绑定的GameObject,SetActive(false)时,也会停止协程

相关文章

网友评论

      本文标题:四、生命周期:2、协程详解

      本文链接:https://www.haomeiwen.com/subject/fdjdlltx.html