循环冻结Unity3D中的游戏

我一直在与while循环斗争,因为他们几乎没有为我工作。 它们总是导致我的Unity3D应用程序冻结,但在这种情况下我真的需要它才能工作:

bool gameOver = false; bool spawned = false; float timer = 4f; void Update () { while (!gameOver) { if (!spawned) { //Do something } else if (timer >= 2.0f) { //Do something else } else { timer += Time.deltaTime; } } } 

理想情况下,我希望那些if语句在游戏运行时运行。 现在它崩溃了程序,我知道它是while循环,这是问题,因为它随时冻结,我取消注释。

每帧都调用Update() ,因此除非在特殊情况下,否则不应在其中使用while循环。 这是因为游戏屏幕冻结直到退出循环。

进一步阅读: https : //docs.unity3d.com/Manual/ExecutionOrder.html

相反,要么像@Programmer那样使用协程,要么使用if / switch语句代替布尔检查。

 bool gameOverActionDone = false; void Update () { if (!gameOver && !gameOverActionDone) { if (!spawned) { //Do something gameOverActionDone = true; } else if (timer >= 2.0f) { //Do something else gameOverActionDone = true; } else { timer += Time.deltaTime; //either keep this here, or move it out if the if condition entirely } } } 

如果你想使用一个变量控制一个while循环并在while循环中等待,那么在一个coroutine函数中执行它并在每次等待后yield 。 如果你不屈服,它会等待太多,Unity会冻结。 在像iOS这样的移动设备上,它会崩溃。

 void Start() { StartCoroutine(sequenceCode()); } IEnumerator sequenceCode() { while (!gameOver) { if (!spawned) { //Do something } else if (timer >= 2.0f) { //Do something else } else { timer += Time.deltaTime; } //Wait for a frame to give Unity and other scripts chance to run yield return null; } }