Hi Guys,
I’m a Unity newbie needing help with my script. I have a countdown timer while the level is being played as well as a stopwatch timer calculating how long it took for the level to be completed on the result screen. The issue I have is the stopwatch is not calculating the time correctly and I’m not sure why it is wrong. Any help is appreciated.
Here is my script:
public class Timer : MonoBehaviour {
public static float curSeconds = 59;
public static float curMinutes = 4;
public static float startSeconds = 0;
public static float startMinutes = 0;
public static float startTime = 0;
public static float finishTime;
void Start () {
GameObject.Find ("TimerText").guiText.text = "Time Remaining: " + curMinutes.ToString("f0") + ":0" + curSeconds.ToString("f0");
guiText.material.color = Color.black;
}
//Stopwatch Time
void OnLevelWasLoaded(int level) {
if (level == 5)
finishTime = (curMinutes + curSeconds) - (startMinutes + startSeconds);
GameObject.Find ("TimeSpentText").guiText.text = " " + finishTime.ToString();
guiText.material.color = Color.black;
}
// Countdown Timer
void Update () {
startTime = startMinutes + startSeconds;
startTime = Time.time;
if(curSeconds <= 0) {
curSeconds = 59;
if(curMinutes >= 1)
{
curMinutes--;
}
else {
curMinutes = 0;
curSeconds = 0;
// This makes the guiText show the time as X:XX. ToString.("f0) formats it so there is no decimal place.
GameObject.Find ("TimerText").guiText.text = curMinutes.ToString("f0") + ":0" + curSeconds.ToString("f0");
}
}
else {
curSeconds -= Time.deltaTime;
}
//These lines will make sure the time is shown as X:XX and not X:XX.XXXXXX
if(Mathf.Round(curSeconds) <= 9) {
GameObject.Find ("TimerText").guiText.text = curMinutes.ToString("f0") + ":0" + curSeconds.ToString("f0");
}
else {
GameObject.Find ("TimerText").guiText.text = curMinutes.ToString("f0") + ":" + curSeconds.ToString("f0");
}
}
}