- Home /
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?
Answer by azzogat · Jan 16, 2011 at 05:50 PM
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.
Your answer
Follow this Question
Related Questions
Countdown Timer Help About putting 0's 1 Answer
Timer counts down unwanted 2 Answers
How to stop a timer with GUI button? 1 Answer
Countdown timer in minutes:seconds:milliseconds 2 Answers
Timer not work :( 0 Answers