Unity - IEnumerator's yield return null

坚强是说给别人听的谎言 提交于 2019-11-28 10:16:39
Everts

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.

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.

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