Creating a timer (415785)

Hi,
I’m having trouble creating a timer to do something. What I’m trying to work out is when the timer reaches 3 seconds > do something; reset timer = 0.

Here’s a snippet of what I’ve done:

private var timer = 0;

timer = Time.time;
		if(timer == 3)
		{
			print("It works");
			timer = 0;
		}
		Debug.Log(timer);

The program does print out “It works” when it reaches 3 seconds but it doesn’t reset the timer.

Thanks.
-Hakimo

EDIT: I just found out that Time.time and Time.deltaTime are both read only. How do I set it up so I can reset the values?

Here’s the thing, you’re setting it equal to Time.time, so it will never go back to zero. Time.time is the time since the program was started.

What you want to do is increase your timer by Time.deltaTime every frame and check to see if it’s >= 3 instead of ==.

Thanks for the reply. I’ve edit the code and it works but had to tweak it. I thought Time.deltaTime counts its values in seconds but I actually have to test the values myself to get the amount of time I wanted.

Here’s the snippet:

		timer += Time.deltaTime +1;
		if(timer >= 180)
		{
			print("It works");
			timer = 0;
		}
		Debug.Log(timer);

Now, it will take more or less 3 seconds to do something :slight_smile:

Thanks again.

Yeah deltaTime returns a float representing elapsed time since the last frame; it is very precise like that so testing for an accumulatedValue > targetValue is the way to go there.

heres a link of a clock i made, it does what your trying to do, however its not efficient as it will most likly end up crashing (would take a long time though)

http://forum.unity3d.com/viewtopic.php?t=54773