A
A
Anton Vertov2017-07-13 18:21:59
C++ / C#
Anton Vertov, 2017-07-13 18:21:59

How to make a reverse timer with minutes?

Good day. I want to make a reverse timer in the game, with minutes like this: 01:30 (minute:seconds).
The timer itself in seconds is obtained in the simplest way to do this:

public float timer = 90f;

void Update()
{
timer -= Time.deltaTime;
     if(timer <= 0.0f)
     {
              Debug.Log("The END");
     }
}

But I can't figure out how to make minutes, if let's say 90 seconds in the timer, or 120, exactly like this: 01:30 (01 - minutes, 30 seconds).
Please advise, thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-07-13
@1Frosty

For such a case, it's better to use DateTime and TimeSpan along with formatting patterns :

using System;
using UnityEngine;

public class TimerTest : MonoBehaviour
{
    public float timer = 90;

    private DateTime timerEnd;

    private void Start()
    {
        timerEnd = DateTime.Now.AddSeconds(timer);
    }

    private void Update()
    {
        TimeSpan delta = timerEnd - DateTime.Now;
        Debug.Log(delta.Minutes.ToString("00") + ":" + delta.Seconds.ToString("00"));
        if (delta.TotalSeconds <= 0)
        {
            Debug.Log("The END");
        }
    }
}

It is important to remember that with this method Time.timeScale will not be taken into account , if you need it, then you can store a float with time instead of DateTime in the same way, but then you will have to calculate the minutes yourself. I do not advise you to add deltaTime in the update. Theoretically, you can still use Timer , but I heard that it does not work on all platforms.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question