Timers can be quite useful in your projects especially when you want to make a Time-Trail level or for example limiting a quest or an even to a timer.
Yet displaying them in the UI is not that straight forward.
Objective: Displaying a timer in the UI
Say that you want to use a timer of 5 minutes which would amount to 300 seconds.
The easiest way to display it in your UI would be to simply decrement your seconds by Time.deltatime and you would get something like this…
For the player this would not be a little confusing when you have that many of a seconds.
What you want to do is display minutes, seconds and if you want the milliseconds in your timer. To achieve this we are going to use something called a Modulus Operator.
Without getting into too much details, simply put the modulus operator (represented using %) determines the whole number remainder of a division operation. So for example 2 % 1 = 0. For more information please read the following blog by Matthew J. Clement.
So back to our example, we want to display a 5 minutes timer.
To display minutes you would simply divide 300 seconds by 60 seconds.
To display seconds, we use 300 seconds modulus 60 seconds (300%60)
To display milliseconds, we multiply 300 seconds by 100 and then use modulus 60. ( (300 * 100) % 60)
And finally in order to display them properly we use each operation with Mathf.FlootToInt in order to display the largest integer smaller or equal to the result.
Here is the final code and result…
The result is a clean timer, and you can even extend this to display hours and days if you need.