Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c# - While loop freezes game in 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;
        }
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to use a variable to control a while loop and wait in that while loop then do it in a coroutine function and yield after each wait. If you don't yield, it will wait too much and Unity will freeze. On mobile devices like iOS, it would crash.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...