Timer is buggy how to fix?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Gametimer : MonoBehaviour
{
    public Text timerLabel;

   [SerializeField] private float time;

    void Update()
    {
        time += Time.deltaTime;

        var minutes = time / 60; //Divide the guiTime by sixty to get the minutes.
        var seconds = time % 60;//Use the euclidean division for the seconds.
        var fraction = (time * 100) % 100;

        //update the label value
        timerLabel.text = string.Format("{0:00} : {1:00} : {2:00}", minutes, seconds,fraction);

    }
}

When the timer reaches 30 seconds it doesnt adds 1 minute for some reason even though i want it to reach 60 to add 1 minute how do i fix this?

Try adding “f” to your numbers… “60” is an integer, “60f” is a float, you may be triggering some round-off.

Just FYI, % is the “modulus” operator (technically the modulo is the remainder from a euclidean division operation).

Actually, the problem is the opposite. 60 should indeed be treated as an integer, but to get the desired math with the division and remainder operators, so should the time field. Otherwise, the 60 gets converted to a float in order to match time, and a floating point division and remainder will do the wrong thing for this type of computation. Try the following:

        var minutes = Mathf.FloorToInt(time) / 60; //Divide the guiTime by sixty to get the minutes.
        var seconds = Mathf.FloorToInt(time) % 60;//Use the euclidean division for the seconds.
        var fraction = Mathf.FloorToInt(time * 100) % 100;
1 Like