How To: Second Clock in Unity

Posted in | How To, Unity

I’ve been asked more than you’d think on how to build a second timer in Unity. It’s straght forward, and involves only a few lines of code.

#pragma strict

var startedAt 		: float;
var clockTime 		: int;
var lastClockTime 	: int;

function Awake(){
	startedAt = Time.time;
}

function Update (){
	var offsetTime : float = Time.time - startedAt;
	clockTime = offsetTime % 60;

	if(clockTime > lastClockTime){
		lastClockTime = clockTime;
		print(clockTime);
	}
}

The way this works is we store Time.time at Awake() so that we account for whatever time passes before our timer starts. On update we subtract that amount from the current time, and then we store the result of the remainder on the clockTime variable.

Finally we check to see if clockTime is different from lastClockTime, and if it is, we update lastClockTime and print the result. We do this to avoid unnecessarily updating the GUI or, in this example’s case, printing the result of the update. This keeps the overhead as low as possible.