Unity-IEnumerator的收益率返回null [英] Unity - IEnumerator's yield return null

查看:140
本文介绍了Unity-IEnumerator的收益率返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试了解IEnumerator&在Unity上下文中的协程,并且对"yield return null"的性能不太确定.目前,我相信它基本上会暂停并等待下一帧,在下一帧中它将返回以再次执行while语句.

I'm currently trying to understand IEnumerator & Coroutine within the context of Unity and am not too confident on what the "yield return null" performs. At the moment i believe it basically pauses and waits for the next frame and in the next frame it'll go back to perform the while statement again.

如果我忽略了收益率归零",似乎该对象将立即移动到其目的地,或者可能跳过很多帧".因此,我想我的问题是,在while循环中此"yield return null"函数的功能是什么,为什么要拥有它呢?

If i leave out the "yield return null" it seems the object will instantly move to its destination or perhaps "skip a lot of frames". So i guess my question is how does this "yield return null" function within this while loop and why is it necessary to have it.

void Start () {
    StartCoroutine(Move());
}

IEnumerator Move(){

    while (a > 0.5f){

        ... (moves object up/down)

        yield return null; // <---------
    }

    yield return new WaitForSeconds(0.5f);

    .... (moves object up/down)

    StartCoroutine(Move());
}

推荐答案

该程序将启动循环,如果没有屈服,它将仅在同一帧内运行所有迭代. 如果您有数百万次迭代,那么很可能会阻塞您的程序,直到完成所有迭代然后继续.

The program will start the loop, if you had no yield, it simply runs all iterations within the same frame. If you had millions of iterations, then it would most likely block your program until all iterations are done and then continue.

创建协程时,Unity会将其附加到MonoBehaviour对象.它将首先在调用StartCoroutine时运行,直到达到产量为止.然后它将从协程返回,并根据产量将其放置在堆栈上.如果产生null,则它将在下一帧再次运行.协程可以返回许多不同的YieldInstruction,您可以在此处和此处了解更多信息.通过相关链接.

When creating a coroutine, Unity attaches it to a MonoBehaviour object. It will run first on call for the StartCoroutine until a yield is hit. Then it will return from the coroutine and place it onto a stack based on the yield. If you yield null, then it will run again next frame. There are a number of different YieldInstruction's that can be returned from a coroutine, you can read more about them here and through the related links.

协程产生后,主线程将继续运行.在下一帧中,Unity将找到堆叠的协程,并将以停产的位置对其进行调用. 如果协程永远不会超出范围,那么您基本上就创建了一个更新方法.

Once a coroutine has yielded, the Main Thread continues running. On the next frame, Unity will find stacked coroutine and will call them from where they left off at the yield. If your coroutine never runs out of scope then you basically created an update method.

协程的目的是执行可能跨越一段时间的操作,而不会阻塞程序.

The purpose of coroutine is to perform actions that could span over a period of time without blocking the program.

重要事实:这不是多线程.

IMPORTANT FACT: this is not multi-threading.

这篇关于Unity-IEnumerator的收益率返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆