Unity3D – Game Engine – Stop and Resume Timer – JavaScript

A Stop and Resume Timer is very useful in video games!

Create an Empty Object and assign Timer.js:


#pragma strict

var myTimer : float; // start value for the timer
var defTime : int; // the reset value
var isCounting : boolean = false; // true while time running
var countUp : boolean = false; // false to count 10...9...8...7...6 true to count 0...1...2...3...4
var GuiText : GUIText; // display timer values

function Start () {
}// END Start()

function Update () {
	Timer();
}// END Update()

function Timer() {
	if(myTimer <= 0){
			myTimer = 0.0; // we do not need negative time!
		}

		if(isCounting && !countUp){
			myTimer -= Time.deltaTime; // count 10...9...8...7...6
		}
			
		if(isCounting && countUp){
			myTimer += Time.deltaTime; // count 0...1...2...3...4
		}

		if(Input.GetKeyDown(KeyCode.R)){ // Reset at defTime
			myTimer = defTime;
		}

		if(Input.GetKeyDown(KeyCode.S)){ // start or stop timer
			isCounting = !isCounting; // invert value of isCounting boolean variable
		}

		GuiText.text = myTimer.ToString("F0"); // display timer values
	}//END Timer()

Inspector> DRAG AND DROP a ‘GUI Text’ over the var GuiText

Inspector> setup var myTimer= 10, var countUp= uncheck, it will count 10…9…8…7…6
OR
Inspector> setup var myTimer= 0, var countUp= check, it will count 0…1…2…3…4

Play, S to start and stop, R to reset.