I’m working on a simple racing game and I want to add a countdown timer, but I can’t get it to work. Any advice after seeing the code?
public float countdown;
void Start()
{
Time.timeScale = 0f;
}
void Update()
{
countdown -= Time.deltaTime;
if (countdown < 0)
{
Time.timeScale = 1f;
}
else if (countdown > 0)
{
Time.timeScale = 0f;
}
}
Since you initially set Time.timeScale to 0, Time.deltaTime is always going to be 0.
(note - Time.timeScale changes the timeScale for everything in the current scene, not a single object.)
Here’s a small script I created for a countdown:
using UnityEngine;
using System.Collections;
public class Countdown : MonoBehaviour {
public float countdown = 10.0f; //The amount of time to wait
private float _time = 0; //The current progress
private bool called = false; //If the countdown has been met.
void Update()
{
if (!called)
{
_time += Time.deltaTime;
if (_time >= countdown)
{
called = true;
DoStuff();
}
}
}
void DoStuff()
{
}
}
I did it this way because of the nature of your question. Due to your statement about how it is a racing game, I assumed you would want an onscreen countdown of sorts, of which this script supports. If you did not want to do an OnScreen countdown, then you could simply do:
public class Countdown : MonoBehaviour {
public float countdown = 10.0f; //The amount of time to wait
void Start()
{
Invoke("DoStuff", countdown);
}
void DoStuff()
{
}
}