- Home /
Timer going negative...Help
Hi, I found this code here and changed it a lit bit since I wanted hours to be displayed too. I achieved this, yay, but when the timer reaches 00:00:00 instead of stopping it keeps counting but like this 00:00:0-1 and so on. Is there anything I'm not doing or doing the wrong way? Any help will be really appreciated!
using UnityEngine; using System.Collections;
public class teste : MonoBehaviour { private float _startTime; private float _restSeconds;
private int _roundedRestSeconds;
private float _displaySeconds;
private float _displayMinutes;
private float _displayHours;
public int CountDownSeconds;
private float _timeLeft;
private string _timetext;
// Use this for initialization
void Start()
{
_startTime = Time.deltaTime;
}
void Update()
{
Timer();
}
void OnGUI()
{
GUI.Label(new Rect(650, 100, 200, 40), _timetext);
}
void Timer()
{
_timeLeft = Time.time - _startTime;
_restSeconds = CountDownSeconds - (_timeLeft);
_roundedRestSeconds = Mathf.CeilToInt(_restSeconds);
_displaySeconds = _roundedRestSeconds % 60;
_displayMinutes = (_roundedRestSeconds / 60) % 60;
_displayHours = (_roundedRestSeconds / 3600);
_timetext = string.Format("{0:00}:{1:00}:", _displayHours, _displayMinutes);
if (_displaySeconds > 9)
{
_timetext = _timetext + _displaySeconds.ToString();
}
else
{
_timetext = _timetext + "0" + _displaySeconds.ToString();
}
if (_displayHours == 0 && _displayMinutes == 0 && _displaySeconds == 0)
{
Debug.Log("The end!");
}
}
}
Answer by Mmmpies · Feb 07, 2015 at 11:37 AM
Set a bool let's say
private bool useTimer = true;
Then in Update:
if(useTimer)
Timer();
and in your if check:
if (_displayHours <= 0 && _displayMinutes <= 0 && _displaySeconds <= 0)
{
Debug.Log("The end!");
useTimer = false;
}
Answer by Bunny83 · Feb 07, 2015 at 11:29 AM
edit Sorry had it wrong in the beginning because of the naming of yoru variables ^^ "_timeLeft" isn't the time left but the time passed. It's increasing. I fixed it...
Line 31, instead of
_restSeconds = CountDownSeconds - (_timeLeft);
do this:
_restSeconds = Mathf.Max(0, CountDownSeconds - _timeLeft);
The Max function returns the greater value of those passed to the function. So usually (Time.time - _startTime) is larger and is returned. But when it becomes negative the "0" is greater so the 0 is returned.
Answer by NoseKills · Feb 07, 2015 at 11:38 AM
You could for example do _roundedRestSeconds = Mathf.Max(0, Mathf.CeilToInt(_restSeconds));
. The source of all your time strings is _roundedRestSeconds
so just make sure that never goes below 0.
Also I think it should be
void Start()
{
_startTime = Time.time;
}
since in Update you are counting time passed from Time.time ?
Your answer
Follow this Question
Related Questions
Countdown timer into text c# 1 Answer
Problems in c# countdown timer 1 Answer
How do i restart my game if countdown timer runs out on a scene 3 Answers
how to Subtract string from TimeSpan 0 Answers