Milliseconds Timer Question
Am I getting the milliseconds correct at the moment and how do I make it so that they stop at 1000 and don't just keep going? Also I will want to make them appear as just two digits but I think theres already a question covering that. Any help would be much appreciated!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour {
public Text counterText;
public float milliseconds, seconds, minutes, hours;
void Start () {
counterText = GetComponent<Text> () as Text;
}
void Update () {
hours = (int)(Time.timeSinceLevelLoad / 3600f);
minutes = (int)(Time.timeSinceLevelLoad / 60f);
seconds = (int)(Time.timeSinceLevelLoad % 60f);
milliseconds = (int)(Time.timeSinceLevelLoad * 6f);
counterText.text = hours.ToString ("00") + ":" + minutes.ToString ("00") + ":" + seconds.ToString ("00") + ":" + milliseconds.ToString("00");
}
}
Answer by Eno-Khaon · Jul 01, 2016 at 06:22 PM
The basic unit of Time in Unity is 1.0 per second. It's why your implementation of seconds is correct as-is.
However, all your other units are off slightly. For example, 1 hour, 20 minutes, 36 seconds would display as something like 1:80:36
at present.
To account for this, ensure that your minutes are rolled over in the same manner as seconds are:
minutes = (int)(Time.timeSinceLevelLoad / 60f) % 60;
As for milliseconds, it's a simple application of the metric prefix milli-. Because 1.0 in time = 1 second, you can multiply that by 1000 for an integer value of milliseconds.
milliseconds = (int)(Time.timeSinceLevelLoad * 1000f) % 1000;
Don't forget to reset the value every second.
Finally, we get to the text formatting. Based on your example, I'm guessing you intend to always display two digits per number displayed, so I'll work on that assumption...
Microsoft keeps some handy documentation on Standard Numeric Format Strings which gives us some useful tools here. Namely, because all your values are converted into integers, you can make use of the "Decimal" listing.
counterText.text = hours.ToString ("D2") + ":" + minutes.ToString ("D2") + ":" + seconds.ToString ("D2") + ":" + milliseconds.ToString("D2");
Thank you very much for taking the time to give such a detailed answer it really helped me out!