Forgive me, I am a complete beginner but I can’t find this answer anywhere. I’m trying to creating a simple countdown timer which I have done. My problem is that the timer seems to print out and count down from two numbers. One, the value I supply to the seconds variable either in the code below or via the Unity component. Two, zero. The first number seems to work as I intend and stop counting down at 0, but the second number will continue to decrease.
Can someone tell me what I’ve done wrong? I’ve put my code in below.
Thanks
var seconds = null;
function Start () {
InvokeRepeating ("Countdown", 1.0, 1.0);
}
function OnGUI(){
GUI.Label(Rect(10, 10, 60, 20), "Time : " + seconds);
}
function Countdown () {
seconds -= 1;
if (seconds == 0){
CancelInvoke ("Countdown");
}
}
Have you checked to see that this GameObject is the only one you have with this Timer script? If it’s somewhere else, it could be decrementing at the same time, but the 2nd one wasn’t set to a value and was starting at 0.
However, if you wanted to have 2 timers running, then this could be a scope issue. From the looks “var seconds” is globally accessible. I don’t know Javascript, but I’m going to guess it’s likely that if there were 2, they are sharing that seconds value. What would happen then is that Timer1 would call Countdown, decrement seconds, and then see it was 0 and cancel the invoke. However, Timer2 in another object is using that same second value, so when it’s Countdown function calls, it does seconds = 0 -1, if (seconds == 0) cancel.
No, it’s the same as in C#, where class variables are an instance. You need to make variables static for them to share the same value.
Yes.
This should be:
var seconds = 10; // or some other integer
or
var seconds : int;
It can’t infer the type if you assign null, and also integers can’t be null. The actual problem though is what Mariol said, where you have that script on more than one object.