In my application I have a countdown timer with a button that decreases the seconds by 30. It works while the seconds are greater than 30 but if its less and I press the button again the seconds give me a negative value and the minutes begin to decrease every second!
Here is my code:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public sealed class Timer: MonoBehaviour
{
public static float minutes = 0f;
public static float seconds = 0f;
private bool _stopTime;
private Text _minuteCounter;
void Start()
{
InitializeTime();
}
public void InitializeTime()
{
minutes = 29;
seconds = 10;
_minuteCounter = GetComponent<Text>();
StartCoroutine(WaitForSeconds());
}
void Stop()
{
_stopTime = !_stopTime;
}
IEnumerator WaitForSeconds()
{
while (true)
{
yield return new WaitForSeconds(1);
if (_stopTime) continue;
seconds--;
if (seconds <= 0)
{
seconds = seconds % 60;
minutes--;
}
GetComponent<Text>().text = string.Format("{0:0}:{1:00}", minutes, seconds);
}
}
}
I know the error occurs in the if clause but I don’t know how to fix it. Can anyone help me figure this out? Many thanks in advance.