- Home /
How to calculate seconds correctly
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.
Answer by gjf · Feb 09, 2017 at 03:07 PM
if (seconds < 0)
{
seconds = 59;
minutes--;
}
_minuteCounter.text = string.Format("{0:0}:{1:00}", minutes, seconds);
Answer by MarshallN · Feb 09, 2017 at 03:38 PM
Try putting a Debug.Log in the if( seconds
if (seconds <= 0)
{
seconds = seconds % 60;
Debug.Log(seconds.ToString());
minutes--;
}
and see what kinda output you're actually having.
The % operator in C# can give negative results, check out the reference.
A good way to fix this would be to keep 'seconds' as your only time variable, and have
displaySeconds= seconds % 60;
displayMinutes =seconds /60;
GetComponent<Text>().text = string.Format("{0:0}:{1:00}", displayMinutes, displaySeconds);
to keep track of minutes and seconds.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to define a slider on script file? 1 Answer
How to make buttons have sound when it is highlighted and clicked? 0 Answers