Hi, can anyone give me please a time counter script? I have one but it don’t works how i want. I want to be hours/minutes/seconds(ex: 01:07:25.43). The problem is that i want the timer to activate only when i press a button, and when the button is pressed again the timer will start from where it remained.
Here is my script:
public Text timerText;
private float startTime;
// Use this for initialization
void Start () {
startTime = Time.time;
}
// Update is called once per frame
void Update () {
float t = Time.time - startTime;
string hours = ((int)t / 3600).ToString ();
string minutes = ((int)t / 60).ToString ();
string seconds = (t % 60).ToString ("f2");
timerText.text = hours + ":" + minutes + ":" + seconds;
}
}
If you want to convert time to string format. Why not use TimeSpan? It way more easy!
void Update()
{
System.TimeSpan result = System.TimeSpan.FromSeconds(startTime);
System.DateTime actualResult = System.DateTime.MinValue.Add(result);
timerText.text = actualResult.ToString("hh:mm:ss");
//Or if you want old way.
timerText.text = result.Hours + ":" + result.Minutes + ":" + result.Seconds;
}
But at first I see you want time counter. You can just add bool variable for it.
public bool timeTick;
Then at update. If you press key. You can just do this.
void Update()
{
timeTick = Input.GetKey(Keycode.F);
//If it true
if (timeTick)
{
startTime = Time.time;
}
}
You haven’t reduced t by the hours when you calculate the minutes. So you’ll get correct number of hours the the full time for minutes.
Try
string hours = ((int)t / 3600).ToString ("00");
float m = t % 3600;
string minutes = ((int)m / 60).ToString ("00");
string seconds = (m % 60).ToString ("00");
Not got access to Unity ATM so can’t test it - sorry.
EDIT - for some reason the format screwed up on the code so I’ve put it as an answer for now.
public Text timerText;
private float startTime;
// Use this for initialization
void Start () {
startTime = Time.time;
}
// Update is called once per frame
void Update () {
float t = Time.time - startTime;
string hours = ((int)t / 3600).ToString ("00");
float m = t % 3600;
string minutes = ((int)m / 60).ToString ("00");
string seconds = (m % 60).ToString ("f2");
timerText.text = hours + ":" + minutes + ":" + seconds;
if (Input.GetButtonDown("Right")) {
startTime = Time.time;
}
}
}
@Toon_Werawat @Mmmpies this is how the scrip ended. It’s exactly what i needed, but when i press the button, it starts from 0. I want to start from where it left.
Guys it’s very simple.
Try this one
##CountDown In hours, Minutes and seconds #
countDown -= Time.deltaTime;
countDownText.text = (((Mathf.Floor(countDown / 3600f)) % 60).ToString("00")) + ":" + (((Mathf.Floor(countDown / 60f)) % 60).ToString("00")) + ":" + (Mathf.Floor(countDown % 60f).ToString("00"));
@Basakot