This post shows how to add a Simple Countdown Timer in Unity and how to use it for your own use case depending on your application or game.
This post shows a how to add a Simple Countdown Timer in Unity and also how you can use it for your own use-case depending on your application or game. Also, learn how you can use the script to have a countdown timer to start a game in Unity. Follow simple and effective steps to add a countdown timer to your unity3D game or app.
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour
{
public float timeLeft = 3.0f;
public Text startText; // used for showing countdown from 3, 2, 1
void Update()
{
timeLeft -= Time.deltaTime;
startText.text = (timeLeft).ToString("0");
if (timeLeft < 0)
{
//Do something useful or Load a new game scene depending on your use-case
}
}
}
Simple steps to follow.
Here is a simple tutorial to add a countdown timer in unity using a c# script.
1. Create a C# Script called StartGame and copy the code from above and paste into it.
2. Add this component to the Main Camera in the scene.
3. Drag and drop the text component on to the script as shown in the image below.
For example, You can drag and drop your text component, in this case, it is countdown as highlighted which will display the countdown text onto the Start Text section of the Start Game Script.
We make the startText field public so that we can drag and drop the Text component directly onto the Start Game Script.
You can also use this script to enable or disable GameObjects before and after the countdown. For example, in this game, I show the text “Tap to Fly” along with the Countdown text. Once the countdown is over, I disable the two text components and destroy them. You can also load a new game scene once the countdown is complete.
4. That's it. You can now click the play button in unity to see the Countdown Timer in action. For example, Here is a sample screenshot of a simple working example.