Good way of implementing a timer?

I’ve tried to implement a timer that should count 10 seconds.

Since this approach crashes it does not seem to be a good implementation. I don’t know why though, because it shouldn’t initiate an infinite loop or anything, should it?

Is there a better alternative?

var startTime: float; 

function Update () {
	if (a particular button is pressed) 
	{
		startTime = Time.time;
		fn_Timer();
 	}
}

function fn_Timer () 
{ 
 	var currentTime = Time.time;
 	var elapsedTime = currentTime - startTime;
 	
 	if ( elapsedTime > 10 ) {
 		// Do other stuff after timer has ended
 	}
 	else {	
 		// Call:	Timer again
 		fn_Timer();	
 	}
}

Apparently, there was a great simple way of doing this that I totally forgot about:

yield WaitForSeconds (10);

And here is a version to handle countdown AND something happening each second.

	for (var n = 10; n > 0; n--)
	{
		yield WaitForSeconds (1);
		
		// Do something each second
	}

Good boy, Unity, here’s a bisquit for being so awesome :slight_smile:

Given your usage scenario (repeater action on top of timer requirement) check out the 4 Invoke methods as well: