I am having issues with my clock script: The problem is:
When the seconds get 60, the scripts goes crazy!
using UnityEngine;
using System.Collections;
public class Clock : MonoBehaviour {
public float seconds = 0;
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;
// Update is called once per frame
void Update () {
if (!isBusy){
isBusy = true;
seconds = (int) Time.time;
if (seconds <=9 && minutes <=9 && hours <=9)
{
textd.Text = "0" + hours + ":0" + minutes + ":0" + seconds;
}
else if (hours <=9 && minutes <=9)
{
textd.Text = "0" + hours + ":0" + minutes + ":" + seconds;
}
else if (minutes <=9)
{
textd.Text = hours + ":0" + minutes + ":" + seconds;
}
else if (hours <=9)
{
textd.Text = "0" + hours + ":" + minutes + ":" + seconds;
}
else
{
textd.Text = hours + ":" + minutes + ":" + seconds;
}
if (seconds == 60)
{
seconds = 0;
minutes+=1;
}
isBusy = false;
}
}
}
This is an Update function called multiple times per frame. Because of that seconds will be == 60 for multiple frames (you setting seconds to 0 doesn’t help, because you set it back to Time on the next frame).
You would be better off add Time.deltaTime to a float and checking when it exceeds 60 and then take 60 off it.
public float time = 0;
...
void Update() {
time += Time.deltaTime;
if(time >= 60) {
minutes++;
time -= 60;
}
Thanks for the script! it works fine! But 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!
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;
}
}
}