While循环冻结Unity3D中的游戏 [英] While loop freezes game in Unity3D

查看:383
本文介绍了While循环冻结Unity3D中的游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用while循环,因为它们几乎对我没有用.它们总是导致我的Unity3D应用程序冻结,但是在这种情况下,我确实需要它正常工作:

I've always struggled with while loops because they barely ever work for me. They always cause my Unity3D application to freeze, but in this instance I really need it to work:

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循环的问题所在,因为只要我取消注释,它就会冻结.

Ideally, I want those if statements to run as the game runs. Right now it crashes the program and I know it's the while loop which is the problem because it freezes anytime I uncomment it out.

推荐答案

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

Update() is called every frame, so you should not use a while loop in it except in exceptional circumstances. This is because the game screen freezes until the loop is exited.

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

相反,要么像@Programmer一样使用协程,要么使用带有布尔检查的if/switch语句.

Instead, either use a coroutine as @Programmer has done, or use an if/switch statement instead, with a boolean check.

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循环冻结Unity3D中的游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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