Unity - IEnumerator's yield return null

房东的猫 提交于 2019-11-27 03:27:24

问题


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.

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());
}

回答1:


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.

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.

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.




回答2:


You are correct. yield return null will wait until the next frame and then continue execution. In your case it will check the condition of your while loop the next frame.

The "why this is necessary" is probably because you want the object to move by an input every frame. Without yield return null it just executes trough the while loop in one frame.

More essential: It looks like you want to Update every frame and adjust the psoition. You could easily use the Update () for that. This function will get called by Unity every frame on an active script.



来源:https://stackoverflow.com/questions/41720221/unity-ienumerators-yield-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!