Making a simple countdown timer
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;
}
}
Answer by DeathDev · May 30, 2016 at 03:31 AM
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()
{
}
}
Okay, the way I have it set works, but how can I make it count down ins$$anonymous$$d? I want to have the text displayed on the screen
Never $$anonymous$$d, I fixed it, I must have missed something when I tried it first, thank you!
Great! Sorry about the late reply, I honestly forgot about this answer for a bit. If you believe that what I provided was the correct answer be sure to mark it! :p
Your answer