It seems like it should be a simple task but it can be surprisingly tricky to display a time value in minutes and seconds in Unity. To display minutes and seconds in a time display, each value must be calculated individually.
10 second timer how to#
How do you convert a float to a time value displayed in minutes and seconds? How to convert a time value to minutes and seconds in Unity Which actually brings me to my next question… I’ve set it to zero when the timer ends because, although it isn’t an issue right now, it can cause a problem when displaying the time value later on.
This is because time is subtracted in chunks, equivalent to the duration of the last frame. This is because the remaining time will almost always be a negative number when the timer stops. You may also notice that, when the timer ends, I’ve manually set timeRemaining to zero. Remember to lock the timer to zero when it ends It also means that the final action, which is triggered when the timer reaches zero, only fires once. This is useful because it allows you to manually control when the timer starts (by setting timerIsRunning to true).
In scripting it looks like this: using System.Collections
10 second timer code#
Once the timer has ended you probably only want to trigger a final action once.īy adding a boolean variable, timerIsRunning, and by wrapping all of the timer’s code inside of an if statement it will only execute it when the timer should be running. This means that whatever action that gets triggered when the timer reaches zero will also be triggered every frame afterwards. There’s just one problem with this method.Īs soon as the timer runs out, the else condition will continue to be true, every frame. The easiest way to do this is with an else condition. There’s no point in having a countdown if nothing happens at the end of it! In the previous example, I used the time remaining to check to see if the timer should still be running or not.īut what if you want to trigger an action when the timer runs out?įor example, you might want to end the game or make the time display flash etc. How to trigger an action when the countdown is finished So long as there is time to count down, the timer will run.Ĭhances are if you’re making a countdown timer, you probably want something to happen when the timer actually reaches zero. This is the basic method for creating a timer in Unity. The method for making a basic countdown timer in Unity is simple.Ĭreate a float variable to store the amount of time remaining and, every frame, subtract the duration of the previous frame (the delta time) from that amount.
10 second timer full#
Or, you can continue below for the full written article instead. I recently made a video of this article, which shows you everything you need to know about making a Countdown Timer in Unity. How to make a timer in Unity (using ltaTime)