美文网首页
[Unity] 协程Coroutine

[Unity] 协程Coroutine

作者: _Walker__ | 来源:发表于2022-05-06 10:18 被阅读0次

      本文的内容是2015-11-27,我在印象笔记里记的踩坑备忘录。然而,最近又遇到了它导致的问题,发现自己慢慢遗忘了这些坑。所以,炒冷饭挪到这边了(印象笔记好多年没登录,怕哪天账号被清)。

    正文

    1、阻塞执行Coroutine有两种方式

    1. yield return StartCoroutine(...)
    2. while(itor.MoveNext()) yield return null;
    对比:

    方式 1

    • 至少会阻塞1帧的时间;
    • 该语句具有原子性,当它所在的协程函数被StopCoroutine时,这里的调用的携程会执行完再退出,不会被打断(前提,其所在的脚本没有被销毁且其所在的GameObject处于激活状态);StopAllCoroutine是可以停止所有协程的;另外这种方式是又开启了一个协程函数,所以暂停一个协程函数是不能停止所有操作的;

    方式 2

    • 在执行只有yield break返回语句(可以有其他非yield语句)的协程时,不会阻塞,会继续执行下面的的语句;
    • 不具有原子性,当主调协程函数被Stop时,它会被中途打断;
    • 当itor指向一个Coroutine对象时,内部协程会失效。如:函数里面使用了
      yield return new WaitForSeconds(x);

    注意:在外层用 2 内层用 1 的协程中,会出现时序混乱的问题,使用时应当留意。

    static IEnumerator Co1()
    {
        IEnumerator itor = Co2();
        Debug.Log("Co Begin:" + Time.frameCount);
        while (itor.MoveNext()) yield return null;
        Debug.Log("Co End:" + Time.frameCount);
    }
    
    static IEnumerator Co2()
    {
        yield return new WaitForSeconds(10);
    }
    
    // StartCoroutine(Co1()) 输出结果如下,中间只隔了1帧,而不是10秒:
    // Co Begin:0
    // Co End:1
    

    2、使用IEnumerator接收协程函数的返回值时,可以使用StopCoroutine结束协程。

    IEnumerator itor = CoroutineFn();
    StartCoroutine(itor);  // 开启协程
    // do somthing...
    StopCoroutine(itor);  // 停止刚开启的协程
    

    相关文章

      网友评论

          本文标题:[Unity] 协程Coroutine

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