Hi! i’m trying to set a simple timer on my game, but currently it’s ugly and goes like this

Script
float time = 0;
void Update ()
{
time += Time.deltaTime;
TimerText.text = "Time: " + time;
}
what’s is the easiest way to change that to a minute and seconds format?
1 Like
Lots of ways, a quick and dirty self-written one could be something similar to:
private static string GetTime(float timeInSeconds)
{
int minutes = ((int)timeInSeconds) / 60;
int seconds = ((int)timeInSeconds) % 60;
return minutes + ":" + ((seconds < 10)? "0" + seconds : seconds.ToString());
}
Not optimal due to GC but it demonstrates the idea.
You could also use the System.DateTime struct or approach this with your custom timer type.
Just to add on a similar note to @Suddoha : if this timer needs to update less frequently, use a coroutine.
larku
4
.NET has some built in support for this:
public static string formatTime(float time)
{
TimeSpan t = TimeSpan.FromSeconds(time);
return string.Format("{0,1:0}:{1,2:00}", t.Minutes, t.Seconds);
}
3 Likes