简体   繁体   中英

How does Unity Engine WaitForSeconds work?

I'm very new to unity engine, I am trying to use waitforseconds function and it doesn't seem to be working. Any help is much appreciated.

Code:

IEnumerator SetCountText(){
        countText.text = "Count: " + count.ToString();
        if (count >= 12) {
            winText.text = "You win!";
            yield return new WaitForSeconds (4);
            NextLevel ();
        }
    }

I call the function in start() function by using startcoroutine( setcounttext());

Thanks in advance!

You mentioned you start your couroutine in the Start() function of the unity script. Start() is only called once, when the script has first initialized.
Considering your coroutine's logic, it only starts once and ends immediately.

If constant checking is desired, what you need is enclosing everything in a while loop:

IEnumerator SetCountText(){
        while (count < 12) {
            countText.text = "Count: " + count.ToString();
            yield return new WaitForSeconds(1);
        }

        winText.text = "You win!";
        yield return new WaitForSeconds (4);
        NextLevel ();
}

What happens now is if the count variable is >= 12 then after 4 seconds, the level changes. Not sure if that is the effect you are trying to achieve.

I have discovered that this function does not work great all of the time , so I wrote my own simple class to sort the problem. I have never had any problems counting seconds with this one.

public class MyCouroutine
{
    public static IEnumerator WaitForRealSeconds(float duration)
    {
        float start = Time.realtimeSinceStartup;
        while (Time.realtimeSinceStartup < start + duration)
        {
            yield return null;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM