making a timer (00:00) minutes and seconds

Ok, so Im trying to make a game timer that increments every second and displays it in the format of MM:SS

Heres what I have

public static float timer;
public static bool timeStarted = false;

void Update ()
 {
    if (timeStarted == true) 
   {
        timer += Time.deltaTime;
    }       
}

void OnGUI()
 {
    float minutes = Mathf.Floor(timer / 60);
    float seconds = timer%60;

    GUI.Label(new Rect(10,10,250,100), minutes + ":" + Mathf.RoundToInt(seconds));
}

but it outputs M:S (if the seconds is over 10 then obviously the seconds will be double digit) would anyone be able to explain where im going wrong?

Actually, there’s a much nicer way of doing this:

void OnGUI() {
    int minutes = Mathf.FloorToInt(timer / 60F);
    int seconds = Mathf.FloorToInt(timer - minutes * 60);

    string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds);

    GUI.Label(new Rect(10,10,250,100), niceTime);
}

This will give you times in the 0:00 format. If you’d rather have 00:00, simply do

    string niceTime = string.Format("{0:00}:{1:00}", minutes, seconds);

There’s a couple of possibilities you have with the formats here: {0:#.00} would give you something like 3.00 or 10.12 or 123.45. For stuff like scores, you might want something like {0:00000} which would give you 00001 or 02523 or 20000 (or 2000000 if that’s your score :wink: ). Basically, the formatting part allows any kind of formatting (so you can also use this to format date times and other complex types). Basically, this means {indexOfParameter:formatting}.

I would imagine there's a cleaner way to do this, but:

float minutes = Mathf.Floor(timer / 60);
float seconds = Mathf.RoundToInt(timer%60);

if(minutes < 10) {
    minutes = "0" + minutes.ToString();
}
if(seconds < 10) {
    seconds = "0" + Mathf.RoundToInt(seconds).ToString();
}
GUI.Label(new Rect(10,10,250,100), minutes + ":" + seconds);

Here I'm just converting the float to a string if the value is less than 10, and sticking a leading zero on. Also, performing the RoundToInt at the variable definition instead of in the GUI.Label call. Haven't had time to actually test it, but that should work.

Here is the example burnumd mentioned:

public float timer;
public string timerFormatted;

void Update()
{
    System.TimeSpan t = System.TimeSpan.FromSeconds(timer);

    timerFormatted = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
}

sorry guys its late but single line solution is here

(totalTimeSec / 60 ).ToString("00")  + ":" + (totalTimeSec%60).ToString("00");

or 

Mathf.Floor(totalTimeSec / 60 ).ToString("00")  + ":" + Mathf.FloorToInt(totalTimeSec%60).ToString("00");

try 2nd solution.

Look into using C#'s string.Format. I'd recommend looking at this StackOverflow exchange which explains using it to display a time however you want it using a TimeSpan which you can create by calling `new System.TimeSpan.FromSeconds (timer)`.

Please ignore my morning sniffles. but heres a video explaining (if it needs it.)

###1

Wow there are some over engineered solutions here.

You could just store the DateTime you triggered the timer and then calculate the timespan by subtracting it from the current time.

    DateTime _timer;

    void Update()
    {
        // Your triggering mechanism just sets the _timer to DateTime.Now Somewhere
        if(Input.GetKeyDown(KeyCode.Space)) _timer = DateTime.Now;

        if(_timer != default(DateTime))
        {
            Debug.Log(DateTime.Now.Subtract(_timer).ToString(@"mm\:ss"));
        }
    }

This is what i made for my countdown timer using UI Text.

public Text TimerText;
public float Minutes;
public float Seconds;

void Start()
{
	StartCoroutine(Wait());
}

void Update()
{
	if(Seconds < 10)
	{
	TimerText.text = (Minutes + ":0" + Seconds);
	}

	if(Seconds > 9)
	{
		TimerText.text = (Minutes + ":" + Seconds);
	}

}

public void CountDown()
{
	if(Seconds <= 0)
	{
		MinusMinute();
		Seconds = 60;
	}

	if(Minutes >= 0)
	{
		MinusSeconds();
	}

	if(Minutes <= 0 && Seconds <= 0)
	{
		Debug.Log("Time Up");
		StopTimer();
	}
	else
	{
		Start ();
	}
	
}

public void MinusMinute()
{
	Minutes -= 1;
}

public void MinusSeconds()
{
	Seconds -= 1;
}

public IEnumerator Wait()
{
	yield return new WaitForSeconds(1);
	CountDown();
}

public void StopTimer()
{
	Seconds = 0;
	Minutes = 0;
}

Guys it’s very simple
for batter result try this one

CountDown In hours, Minutes and seconds

countDown -= Time.deltaTime;

countDownText.text = (((Mathf.Floor(countDown / 3600f)) % 60).ToString("00")) + ":" + (((Mathf.Floor(countDown / 60f)) % 60).ToString("00")) + ":" + (Mathf.Floor(countDown % 60f).ToString("00"));

@CarlLawl

Too many complex answers here!
Because from what’s your question i can see that you are an amateur i suggest you using this simple code:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine.UI;
    using UnityEngine;
    
    public float seconds;
    public float minutes;
    public Text timeCountText;
    
    
    void Start(){
    
    }
    
    void Update(){
    timer += Time.deltaTime;
    if (seconds > 59){
    minutes += 1;
    seconds = 0;
    }
    
    timeCountText.text = minutes.ToString("00") + " : " + seconds.ToString("00");
    
    }
}

private Text m_gameTime;

void Update()
{
    float gameTimer += Time.deltaTime * 600;

    int seconds = (int)(gameTimer % 60);
    int minutes = (int)(gameTimer / 60);
    int hours = (int)(gameTimer / 3600);

    string timerString = string.Format("{0:0}:{1:00}:{2:00}", hours, minutes, seconds);

    m_gameTime.text = timerString;
}

@CarlLawl

, private Text m_gameTime;

void Update()
{
    float gameTimer += Time.deltaTime * 600;

    int seconds = (int)(gameTimer % 60);
    int minutes = (int)(gameTimer / 60);
    int hours = (int)(gameTimer / 3600);

    string timerString = string.Format("{0:0}:{1:00}:{2:00}", hours, minutes, seconds);

    m_gameTime.text = timerString;
}