码迷,mamicode.com
首页 > 编程语言 > 详细

简要分析unity3d中剪不断理还乱的yield

时间:2014-10-29 14:47:38      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   io   ar   使用   for   sp   div   

摘自:http://www.unitymanual.com/thread-23724-1-1.html

首先,先看如下代码.

void Start () {
 
    StartCoroutine(Destroy());
 
}
 
IEnumerator Destroy(){
 
    yield return WaitForSeconds(3.0f);
 
    Destroy(gameObject);

}

  这个函数干的事情很简单:调用StartCoroutine函数开启协程,yield等待一段时间后,销毁这个对象;由于是协程在等待,所以不影响主线程操作。一般来说,看到这里的时候都还不会晕,yield就是延时一段时间以后继续往下执行呗,恩,学会了,看着还蛮好用的。

  当然,yield能干的事情远远不止这种简单的特定时间的延时,例如可以在下一帧继续执行这段代码(yield return null),可以在下一次执行FixedUpdate的时候继续执行这段代码(yield new WaitForFixedUpdate ();),可以让异步操作(如LoadLevelAsync)在完成以后继续执行,可以……可以让你看到头晕。

  unity3d官方对于协程的解释是:一个协同程序在执行过程中,可以在任意位置使用yield语句。yield的返回值控制何时恢复协同程序向下执行。协同程序在对象自有帧执行过程中堪称优秀。协同程序在性能上没有更多的开销。StartCoroutine函数是立刻返回的,但是yield可以延迟结果。直到协同程序执行完毕。(原文:The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.)

  如果只是认为yield用于延时,那么可以用的很顺畅;但是若看到yield还有这么多功能,目测瞬间就凌乱了,更不要说活学活用了。不过,如果从原理上进行理解,就很容易理清yield的各种功能了。

public static IEnumerable<int> GenerateFibonacci()
 
{
 
    yield return 0;
 
    yield return 1;
 
 
    int last0 = 0, last1 = 1, current;
 
 
    while (true)
 
    {
 
        current = last0 + last1;
 
        yield return current;
 
 
        last0 = last1;
 
        last1 = current;
 
    }
 
}

简要分析unity3d中剪不断理还乱的yield

标签:des   blog   http   io   ar   使用   for   sp   div   

原文地址:http://www.cnblogs.com/daxiaxiaohao/p/3970733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!