Timer (447600)

I have 2 scenes in my game. the playing level and the ‘you have failed’ level. I have a button on my fail level to go back to the playing level with a simple application.loadlevel script attached, however my timer is not reset so the playing screen just flashes up. Here is my timer code, i have looked at other forums and I dont understand why it doesnt work. thankyou for any help

var startTime = 30.0;
var timeLeft : float;

function Start ()
{
	startTime = Time.time;
	startTime = 30.0;
}
function Update () {
   //Time left
   timeLeft = startTime - Time.time;
   //Time cannot go below zero
   timeLeft = Mathf.Max (0, timeLeft);
   //Format time
   guiText.text = FormatTime (timeLeft);
   //When time is 0, restart level
   if (timeLeft == 0) {
      Application.LoadLevel ("Level fail");

      }
}


//Format time
//12(minutes):34(seconds).5(fraction)
var intTime : int;
var minutes : int;
var seconds : int;
var fraction : int;

function FormatTime (time) {
   intTime = time;
   minutes = intTime / 60;
   seconds = intTime % 60;
   fraction = time * 10;
   fraction = fraction % 10;
   
   //Build string according to format
   //12(minutes):34(seconds).5(fraction)
   
   timeText = minutes.ToString () + ":";
   timeText = timeText + seconds.ToString ();
   timeText += "." + fraction.ToString ();
   return timeText;
}

Use awake instead of start.

Start is only called first time you load the level.
Awake is called everytime you start the level.

You certainly set that timer up the hard way.

Thanks for your response. I have now changed it to function awake but i am still getting the same proble. Any ideas?

I’d try using the function OnEnable () instead of Awake ()

I would use some debug statements to check your variables.

The logic on your timer looks strange to me.

timeLeft = startTime - Time.time;

Doesn’t Time.time just keep getting bigger as you run. So pretty soon it would be bigger than 30 and create a logic error?

Why don’t you set your startTime and subtract delta time until you get to <0 instead of messing around with Time.time?

I think Time.time counts up from when the game was started, not the level. Time.timeSinceLevelLoad (check API as that was off top of my head) may be from level load.

Yep, as others have said… Time.time is “seconds since the start of the game”. So, once your above logic has tripped the first time (time.time > 30), it’ll forever be > 30 and will trip your LoadLevel call immediately with each successive call…

Jeff

thats exactly right, read more about it here