Problems in c# countdown timer

Hello guys okay?

I’m using the code below to display the counter, the counter starts with 120 seconds and decays. But when I give my scene in the play, the counter begins: 2:59. When he arrives at 2:30, it jumps to 1:29, when he arrives at 1:00, the counter is showing 1:59 and finally when he arrives at 1:30 to 0:29 he jumps and continues to give count normally.

I wonder what is wrong with my script, below:

    using UnityEngine;
    using System.Collections;
    
    public class GameManager : MonoBehaviour {
    	
    	private float theTimer = 0.0f;
    	public float theStartTimer = 120.0f;
    	float displayMinutes;
    	float displaySeconds;
    	
    	void Start () {
    		theTimer = theStartTimer;
    	}
    	
    	void Update () {
    		theTimer -= Time.deltaTime;
    		
    		if (theTimer <= 0) {
    			Debug.Log("Over Time");
    			theTimer = 0;
    		}
    		
    		if (Input.GetKeyUp(KeyCode.G)) {
    			Debug.Log("Reset time");
    			theTimer = theStartTimer;
    			showRemaining = false;
    		}
    	}
    	
    	void OnGUI () {
    		displayMinutes = Mathf.CeilToInt(theTimer) / 60.0f;
    		displaySeconds = Mathf.CeilToInt(theTimer) % 60.0f;
    		string text = string.Format("{0:00}:{1:00}", displayMinutes.ToString("0"), displaySeconds.ToString("0"));
    		GUI.Label(new Rect(10, 110, 100, 20), "Time: " + text);
    	}
    }

Remembering that it compiles and runs normally, only the display of the time you’re crazy.

You need to do two things:

  • use FloorToInt (as alucardj suggested)
  • Do the floor AFTER you do the division or mod operation.

Here is the updated code:

        void OnGUI () {
           displayMinutes = Mathf.FloorToInt(theTimer / 60.0f);
           displaySeconds = Mathf.FloorToInt(theTimer % 60.0f);
           // the rest
        }