- Home /
Countdown Timer
I am trying to make a countdown timer for my game (3, 2,1, Start), but cannot get it to work. The countdown starts, but does not decrease and stays the same number (as though it's frozen). Why is the timer not counting down? I have done a powerup countdown timer so i know I'm close. The canvas and the timescale being set at 0 is making this scenario a little different though. I'd appreciate some help.
Here's my code:
SceneManager:
using UnityEngine .SceneManagement ;
using UnityEngine .UI;
public class ChangeSceneManager : MonoBehaviour {
public static bool GameStarted=false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Play(){
//Time.timeScale = 0f;
GameStarted = true;
SceneFader.instance.FadeIn ("Gameplay");
}
}
Count Down Timer:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDownTimer : MonoBehaviour {
public Text countDownTimer;
private float time = 5.0f;
public static bool startCountDown;
// Use this for initialization
void Start () {
Time.timeScale = 0f;
//ChangeSceneManager.GameStarted = true;
}
// Update is called once per frame
void Update () {
//if(startCountDown==true){
if (ChangeSceneManager.GameStarted == true) {
countDownTimer.enabled = true;
time -= Time.unscaledDeltaTime;
countDownTimer.text=time.ToString ("f0");
if (time < 1) {
countDownTimer.text = "START";
}
if (time <= 0) {
Time.timeScale = 1f;
countDownTimer.enabled = false;
ChangeSceneManager.GameStarted = false;
}
}
}
}
What Hellium said. Alternatively, you could use RealTimeSinceStartup, which doesn't get scaled, and count the difference elapsed since start to the current time.
Answer by blenderblender · Jul 14, 2016 at 06:58 PM
Use a Coroutine to count down.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CountDownTimer : MonoBehaviour {
public int CountDown = 3;
private void Update()
{
if (ChangeSceneManager.GameStarted == true)
{
StartCoroutine(CountDownTimer());
}
if (CountDown == 3)
{
// Ready
}
if (CountDown == 2)
{
// Steady
}
if (CountDown == 1)
{
// Go
}
}
IEnumerator CountDownTimer()
{
yield return new WaitForSeconds(1);
CountDown--;
}
}
I won't be able to use a coroutine if the timescale is set to 0.
Your answer
Follow this Question
Related Questions
Time.timeScale problem 1 Answer
How to start a timer after object is not active? 1 Answer
Count Down Timer.... (per second) 3 Answers
Countdown timer trouble? 1 Answer