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

查看:30
本文介绍了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.

如果我省略yield return null",对象似乎会立即移动到其目的地,或者跳过很多帧".所以我想我的问题是这个 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 可以从协程返回,您可以在 here 和通过相关链接.

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 将找到堆叠的协程,并从它们在 yield 处停止的地方调用它们.如果您的协程从未超出范围,那么您基本上创建了一个更新方法.

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天全站免登陆