Create a Simple Countdown Timer in Unity with C#
Hello programmers, many of us played video games in our lives and every game starts with the timer “3”, “2”, “1”, “GO”. Without this countdown, the game feels empty.
So in this article, we’ll learn how to create a simple countdown timer in Unity with C# code.
Create Text UI
Before creating a text file we first need to create a panel in the Hierarchy.
Go to GameObject > UI > Panel
In the Inspector of Panel click on Add Component > Text. Select Text
Create C# Script
- Go to Assets
- Assets > Create > C# Script
Countdown Timer
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CountdownTimer : MonoBehaviour { public float timeLeft = 3.0f; public Text startText; // used for showing countdown void Update() { timeLeft -= Time.deltaTime; // Convert integer to string startText.text = (timeLeft).ToString("0"); if (timeLeft < 1) { startText.text = "GO"; } } }
Now drag the CountdownTimer Script to Plane, as shown below:-
After adding the script to Plane, now drag Text component to the countdown timer. As shown below:-
Output:
Leave a Reply