- Home /
The question is answered, right answer was accepted
How do I make a counter that goes up by 1 every second?
I am trying to make a Day and Night cycle in unity, and for that I thought I would need some kind of variable that goes up by one every second. I though this would be very simple to make, so I tried this:
var seconds : float = 0.0;
function Update() {
seconds = seconds + (Time.deltaTime);
}
However, something very strange happened - instead of the variable "seconds" going up by 1 every second, as soon as I pressed the play button at the top, the pause button next to it automatically went down with it, and then every time I tried to un-pause the game by pressing the button again, it played for 1 frame, and then paused again immediately afterwards. How has this bit of code manages to pause the game? Is this meant to happen, or have I broken unity somehow?
@Fattie: Right answer accepted? Wouldn't "Problem is not reproducible or outdated" fit better? Anyway... :D
Answer by Golan2781 · Dec 31, 2012 at 12:39 PM
You can directly use the Time.time function to get the game time. You do not need to track it manually.
Generally, if you want something to happen every X seconds, you should look into the invokeRepeat and Coroutine functionality of Unity. InvokeRepeat is most appropriate for things always happening on the same timeframe, like for example toggling day states at fixed intervals. Coroutines are very good for making sequences ('do something every 5 seconds for five times total') or repeating actions with varying time intervals.
Using Update and checking states every frame is a lot more costly and can make cluttered code, though there are many things that need the level of control only Update offers.
On the issue of unity stopping: your code is fine. You should look for the fault at another point in your code.