x


Countdown timer trouble?

I have a script that with the use of a GUIText object, displays the time left before the game is over. The time begins from 15 and reduces. If it reaches 0... game over. I have a question regarding this script:

GUITextTimeLeftEM.js

private var startTime;
static var timeLeftDisplayed : int;
private var timeLeft: float= 15;
var textToShow: GUIText;

function Awake() {
    startTime = Time.time+0.5;
}

function OnGUI () {
    var guiTime = Time.time - startTime;
    timeLeftDisplayed = timeLeft - (guiTime);
    if (timeLeftDisplayed == 0) {
        print ("Time is Over");
        LoadNextLevel ();
    }
}

function Update(){
    textToShow.text = "Time left:   " + timeLeftDisplayed.ToString();
}

function LoadNextLevel () {
        cubeMovementIVEndlessMode.chainHits =0;
        cubeMovementIVEndlessMode.frenzyOn=false;
        yield WaitForSeconds (.5);
        Application.LoadLevel(Application.loadedLevel + 1);
    }

I use

startTime = Time.time+0.5; 

because if I just use:

startTime = Time.time;

the timer goes from 15 to 14 in 0.5" instead of the expected 1". Why is that?

more ▼

asked Jan 16 '11 at 05:33 PM

schwertfisch gravatar image

schwertfisch
370 53 57 68

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

There's quite a few prettier ways to do what you need. What you're doing will not stick because timeLeftDisplayed will be immediately reset to what it should be on the next ongui refresh.

So immediately after you add 1 second it does what you're telling it to do:

timeLeftDisplayed = 15-(Time.time-(gameStartTime+0.5));

If you want to stick to this way of counting down you should actually do

GUITextTimeLeftEM.timeLeft += 1;

(and of course, don't make the variable private)

You should check this question out for a more correct way of counting down. Also remember that OnGui is a performance killer.

P.S: the first part of the answer was for an edited-out part of the question.

more ▼

answered Jan 16 '11 at 05:50 PM

azzogat gravatar image

azzogat
918 3 16

Thanks a lot azzogat :)

Jan 16 '11 at 06:42 PM schwertfisch
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x347
x62
x22

asked: Jan 16 '11 at 05:33 PM

Seen: 883 times

Last Updated: Jan 16 '11 at 05:44 PM