Countdown timer...
In a game I'm making I want to have a countdown timer that starts at 1:00 and goes down to 0:00. I want the timer to be displayed in some text that I have placed down. I have tried for a long time to get this to work but it just won't. Please help me.
Answer by Charmind · Jul 21, 2016 at 08:39 PM
Simple as this:
// Remember using using UnityEngine.UI;
public Text text; // set it to your timer text on GUI
float tim = 60;
void Update()
{
text.text = (Mathf.Floor(tim/(60*60)))+":"+(Mathf.Floor(tim/60)%60)+":"+Mathf.Floor(tim%60);
tim -= Time.deltaTime;
}
Explanation:
1st thing in "text =" is hour counter, next is minute counter modulo 60 so it will display 0-59 minutes and not more because that goes to hour section. Next is seconds modulo 60 because 60 seconds is minute so it displays 0-59 seconds on it.
just in case you dont know what modulo is:
it's symbol is "%" and it returns rest from division, so 20%21 = 20 and 21%21 = 0 22%21 = 1 and so on. just loop of numbers with given lenght.
I'm trying to make it so that when I press the Q button, the timer starts but for some reason it won't. I had the timer working before I stopped it running when the game started... Here's the scripts I'm using.
public class TimeCounter : $$anonymous$$onoBehaviour {
bool startCounter;
public Text text; // set it to your timer text on GUI
float tim = 60;
void Start()
{
startCounter = false;
}
public void StartTimeCounter()
{
startCounter = true;
}
public void StopTimeCounter()
{
startCounter = false;
}
void Update()
{
if (startCounter)
{
print("hmmmm");
text.text = ($$anonymous$$athf.Floor(tim / 60) % 60) + ":" + $$anonymous$$athf.Floor(tim % 60);
tim -= Time.deltaTime;
}
}
}
and this is in another script:
void Update () { if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Escape)) { Application.Quit(); }
//if (scoreUITextGO.GetComponent<GameScore>().Score > 0);
if (Input.Get$$anonymous$$eyDown("q"))
{
print("yay");
TimeCounterGO.GetComponent<TimeCounter>().StartTimeCounter();
}
Thanks
Answer by commodore · Jul 21, 2016 at 08:54 PM
private float timeInSeconds = 60;
void Update() {
float minutes = Mathf.FloorToInt (timeInSeconds / 60);
float seconds = Mathf.FloorToInt (timeInSeconds) % 60;
Debug.Log (string.Format("{0}:{1}", minutes.ToString("0"), seconds.ToString("00")));
timeInSeconds -= Time.deltaTime;
}
Follow this Question
Related Questions
Project Spark to C# - Started To, While, and No Longer 1 Answer
Traffic Light won't change colors State machine 0 Answers
Need to create a Time Trial in Unity with C# 1 Answer
How to get a countdown timer with values entered by the player 0 Answers
Player Countdown Interaction/Time Reduction+Addition 0 Answers