Set limit to 60 seconds

I’m trying to write my own time system and everything is working fine except for one thing:

I want the label GUI to show “00” instead of “60” when the float time gets 60. How could I do that? Thanks! (I’ve tried things like Mathf.Clamp)

Script:

using UnityEngine; using System.Collections;

public class Clock : MonoBehaviour {

``````public int minutes = 1;
public int hours = 22;
public int day = 0;
public float month;
public float year;
public bool isBusy = false;
public dfLabel textd;
public float time = 0;

void Start () {
}

// Update is called once per frame
void Update () {

if (!isBusy){

isBusy = true;

//seconds = (int) Time.time;

time += Time.deltaTime;

if(time >=60) {
time -= 60;
minutes++;
}

if (time <=9 && minutes <=9 && hours <=9)
{
textd.Text = "0" + hours + ":0" + minutes + ":" + time.ToString ("00");

}
else if (hours <=9 && minutes <=9)
{
textd.Text = "0" + hours + ":0" + minutes + ":" + time.ToString ("00");

}

else if (minutes <=9)
{
textd.Text = hours + ":0" + minutes + ":" + time.ToString ("00");

}
else if (hours <=9)
{
textd.Text = "0" + hours + ":" + minutes + ":" + time.ToString ("00");

}

else
{

textd.Text = hours + ":" + minutes + ":" + time.ToString ("0");

}

isBusy = false;

}

}

}
``````

This would probably be better solved with the TimeSpan object, but you could get away with something like this as well:

``````// assuming your `time` variable keeps track of seconds
float seconds = time % 60;
float minutes = time / 60;
float hours = minutes / 60;
minutes = minutes % 60;
hours = hours % 24;

Debug.Log(hours.ToString("D2") + ":" + minutes.ToString("D2") + ":" + seconds.ToString("D2"));
``````

Update to explain the code a bit:

The first line will divide the whole big number by 60 (as in seconds per minute) and keep the remainder. That’s what the modulo operator does - it gives you the remainder of a division (ie. the decimal points).

The second line will simply get the seconds converted to minutes (straight up division by 60).

The third line gets the hours - 60 minutes in every hour.

The fourth and fifth line make sure that minutes never surpass 59 and that hours don’t go beyond 23.

This all means that your clock will effectively reset to 0 after 24 hours, but I’m guessing that’s not a huge problem? The TimeSpan object, as mentioned, will definitely make your life easier when doing these sorts of things - and doesn’t have any logical issues or limitations like my code above

As for the .ToString(“D2”) process, that’s just a habit really. From reading this thread, you are probably better off using .ToString(“00”) - which takes ints and floats without any fuss.

In regards to how you implement it in your code, that’s kind of up to you. Give it a try and ask again if you’re having any specific issues

``````    void Update () {