美文网首页
Unity的协程

Unity的协程

作者: jojo911 | 来源:发表于2018-12-11 17:44 被阅读0次

这篇文章转自:
http://blog.csdn.net/huang9012/article/details/38492937
https://www.cnblogs.com/zsb517/p/4107553.html

为了能在连续的多帧中调用该方法,Unity必须通过某种方式来存储这个方法的状态,这是通过IEnumerator 中使用yield return语句得到的返回值,当你“yield”一个方法时,你相当于说了,“现在停止这个方法,然后在下一帧中从这里重新开始!”。

注意:用0或者null来yield的意思是告诉协程等待下一帧,直到继续执行为止。当然,同样的你可以继续yield其他协程

public class CoroutineTest : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {
        StartCoroutine(SaySomeThings());
    }

    IEnumerator SayHelloFiveTimes()
    {
        Debug.Log("1");
        yield return 0;
        Debug.Log("2");
        yield return 0;
        Debug.Log("3");
        yield return 0;
        Debug.Log("4");
        yield return 0;
        Debug.Log("5");
        yield return 0;
    }

    IEnumerator SaySomeThings()
    {
        Debug.Log("The routine has started");
        yield return StartCoroutine(Wait(1.0f));
        Debug.Log("1 second has passed since the last message");
        yield return StartCoroutine(Wait(2.5f));
        Debug.Log("2.5 seconds have passed since the last message");
    }

    IEnumerator Wait(float duration)
    {
        for (float timer = 0; timer < duration; timer += Time.deltaTime)
            yield return 0;
    }
}

可以单步跟踪 IEnumerator SayHelloFiveTimes() ,看看执行顺序!
另一个是嵌套的协程

yield return new WaitForSeconds(0.2f);
yield return new WaitForEndOfFrame();
1.如果只是等待下一帧执行,用yield return null即可。调用顺序在Update后,LateUpdate前

2.如果有截屏需要,用WaitForEndOfFrame。具体参考官方例子。否则直接用Texture2D.ReadPixel抓取屏幕信息则会报错。

3.此外,用WaitForEndOfFrame还可以让代码在LateUpdate的时序后调用。
https://www.cnblogs.com/hont/p/6477384.html

相关文章

  • XLua里使用协程

    在XLua里如何使用协程?有两种方式 使用Unity协程要想通过unity的StartCoroutine使用协程,...

  • Unity 协程

    unity 里面的协程流程 开始协程 StartCoroutine("DoSomething"); 执行到 yie...

  • C#协程

    Unity中协程的执行原理 UnityGems.com给出了协程的定义: A coroutine is a fun...

  • unity协程

    今天在网上看见一个人的博客,发现对unity Coroutine有深入的了解分享一下 原文出处 unity Mo...

  • Unity的协程

    这篇文章转自:http://blog.csdn.net/huang9012/article/details/384...

  • Unity3D 协程管理

    Unity里面的协程好用,但总是在如何关闭指定协程,尤其是关闭带参数的协程的问题上困惑不已。在本文,笔者带你用最简...

  • 自定义协程模块

    IFramework所有模块总目录 简介 协程在unity中很常见,IF中也有自己的协程。其本质就是通过:yiel...

  • Unity3D协程介绍

    协程介绍 Unity的协程系统是基于C#的一个简单而强大的接口,IEnumerator,它允许你为自己的集合...

  • Unity3d-仿写简单dotween C#扩展方法协程单例工厂

    dotween官网 先验知识:Unity3d-Coroutines协程 Unity3d-C#扩展方法 dotwee...

  • Unity之协程

    协程,又称微线程,纤程。英文名Coroutine。子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B...

网友评论

      本文标题:Unity的协程

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