- Home /
How to reset timer? (C#)
I have a timer script that counts down and I would like the timer to reset when the user clicks on the reset button. I am not sure which value to reset to get the timer to completely restart. Thanks in advance. private float startTime = 0; private float restSeconds = 0; private int roundedRestSeconds = 0; private float displaySeconds = 0; private float displayMinutes = 0; public int CountDownSeconds = 120; private float Timeleft = 0; string timetext = ""; void Start () { startTime = Time.deltaTime; } void OnGUI () { startTime = 0; Timeleft = Time.time-startTime; restSeconds = CountDownSeconds-(Timeleft); roundedRestSeconds = Mathf.CeilToInt(restSeconds); displaySeconds = roundedRestSeconds % 60; displayMinutes = (roundedRestSeconds / 60)%60; timetext = (displayMinutes.ToString() + ":"); if (displaySeconds > 9){ timetext = timetext + displaySeconds.ToString(); } else { timetext = timetext + "0" + displaySeconds.ToString(); } GUI.Label(new Rect(10, 10, 200, 40), timetext); if(GUI.Button(new Rect(50, 10, 200, 40), "Reset")){ Debug.Log("Reset Time"); } }
Answer by Kryptos · Feb 05, 2012 at 08:37 PM
The time is calculated from the difference of Time.time and startTime. To reset your timer, you need to make this difference be zero, i.e.
void ResetTimer()
{
startTime = Time.time;
}
void OnGUI()
{
// your code here
//...
if(GUI.Button(new Rect(50, 10, 200, 40), "Reset")){
Debug.Log("Reset Time");
ResetTimer();
}
Answer by DaveA · Feb 05, 2012 at 01:14 AM
Handle the timer vars in an Update function because OnGUI can be called several times per frame. You can set startTime = 0 if the reset button is pushed.
Answer by hirenkacha · Jun 01, 2012 at 06:42 AM
This will work for you 100%. D
private gameTime=120;
void Start ()
{
CountDownSeconds=gameTime;
startTime = Time.time;
}
void Update ()
{
Timeleft = Time.time-startTime;
restSeconds = CountDownSeconds-(Timeleft);
roundedRestSeconds = Mathf.CeilToInt(restSeconds);
displaySeconds = roundedRestSeconds % 60;
displayMinutes = (roundedRestSeconds / 60)%60;
timetext = (displayMinutes.ToString() + ":");
if (displaySeconds > 9)
{
timetext = timetext + displaySeconds.ToString();
}
else
{
timetext = timetext + "0" + displaySeconds.ToString();
}
GUI.Label(new Rect(10, 10, 200, 40), timetext);
if(GUI.Button(new Rect(50, 10, 200, 40), "Reset")){
Debug.Log("Reset Time");
ResetTimer();
}
if(roundedRestSeconds==0)
{
Application.LoadLevel("LevelLost");
}
}
public void ResetTimer()
{
startTime=Time.time;
CountDownSeconds = gameTime;
}
Let me know if its working fine.
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 Reset Timer on a Collision (C#) 0 Answers
Timer variable set to zero 2 Answers