Timer Display Question

static var timeRemaining : float = 60;
var prefix = "Time Left: ";
var suffix = " ";

function Awake(){
timeRemaining = 60;

}

function Update()
{
guiText.text = prefix + timeRemaining + suffix;

   timeRemaining -= Time.deltaTime;

if(timeRemaining <= 0)
{
Application.LoadLevel ("Game Over");
}
transform.position.x = 0.65;
transform.position.y = 0.05;
}

I have a timer but it displays the numbers after the decimals while I only want it to display whole numbers. Any suggestions?

5 Answers

5

If you want to truncate the time, you could have Unity do the timing for you and then just print that.

var time: int = 60;

function Awake () {
    //Create the timer.
    //Method: InvokeRepeating("MethodName", delayFor1stFire : float, repeatTime: float);
    InvokeRepeating("FireTimer", 1, 1);

    //I could not figure out why you were calling these every frame.
    transform.position.x = 0.65;
    transform.position.y = 0.05;
}

function FireTimer() {
    time--;

    guiText.text = prefix + time.ToString() + suffix;

    if(timeRemaining <= 0)
    {
         Application.LoadLevel ("Game Over");
    }
}

This will improve performance as well because you are not calling the method every frame. Only once per second. So, if performance matters, this is the fastest method.

Oooh, very nice :)

If you just want the ceiling:

guiText.text = prefix + Mathf.Ceil(timeRemaining) + suffix;

If you just want to drop the decimal and get the floor:

guiText.text = prefix + Mathf.Floor(timeRemaining) + suffix;

Simple and effective. I'll take it!

guiText.text = prefix + timeRemaining.ToString("f0") + suffix;

This should work.

You could try Mathf.Round() or something similar, or just convert the float to an int it will drop the fraction.

var intTimeRemaining : int = timeRemaining;
guiText.text = prefix + intTimeRemaining + suffix;

Unity JS has dynamic typecasting, so it should just work. I didn't test it, though.

Cheers

==

Converting the float to an int would make the counting stop, since Time.deltaTime is a float

I believe equalsequals was referring to converting to an int inside the guiText.text, not at your declaration - this would not stop the counting.

How would one do that?

edited my post.

You can use an integer and subtract one every second, instead of using a float in Update. See my answer here: http://answers.unity3d.com/questions/12992/count-down-timer-per-second

I believe that is what I did. ;)

@Peter G: Well, so it is...maybe I should read the other answers more thoroughly next time.... Pity the accepted answers are the less efficient ones. ;)

Hey, I go for simple enough for me to understand. Besides, I openly admit, I'm too incompetent right now to know the difference in the CPU cycle.