Reset time

Hey,
I am trying to create a reset button and am almost there except I can’t work out how to reset the timer.

Here is my code so far:

var gameLength : int = 30;

var timerText : GUIText;


function Update () {


var timeLeft : int = gameLength - Time.time;

	if ( timeLeft < 0 ) {
	
			timeLeft = 0;
			Time.timeScale = 0;
		
		}
	else 
	
		Time.timeScale = 1;
	
		
		timerText.text = "Time Remaining: " +timeLeft;	
	
  }  

function OnGUI () {

			if ( GUI.Button( Rect( 1, Screen.height-25, 75, 25 ), "Restart" )) {
	
		timeLeft = 30;
		Application.LoadLevel( "Pancake game" );
		PancakeCollector.score = 0;
		
	}
}

Ufortunately, setting the variable timeLeft back to 30 when the reset button is hit (as in the above code) does not work because timeLeft is declared in the function Update so only has local scope. When I try and declare timeLeft in global scope (outside a function) I get an error message because you can only access Time.time from within a function.

Any ideas how to get around this?

Thanks so much in advance.

Two things:

  • You should always meassure time in float
  • Use the Time.deltaTime to get the time since last frame

The new script would look something like:

var gameLength : int = 30;

var timerText : GUIText;
var timeLeft : float;

function Start(){
	timeLeft = gameLength;
}

function Update () {
	timeLeft -= Time.deltaTime;


    if ( timeLeft < 0 ) {
		timeLeft = 0;
        Time.timeScale = 0;
    } else {
        Time.timeScale = 1;
	}
	timerText.text = "Time Remaining: " +timeLeft;  
}  

function OnGUI () {

	if ( GUI.Button( Rect( 1, Screen.height-25, 75, 25 ), "Restart" )) {
        timeLeft = 30;
        Application.LoadLevel( "Pancake game" );
        PancakeCollector.score = 0;
	Debug.Log("Time is restarted");
    }
}