Unity Countdown Timer Tutorial | Unity Tutorial
In this video tutorial, we’ll create a countdown timer in Unity using C#. You’ll learn how to implement a straightforward script that counts down from a specified time and displays the remaining seconds on the screen.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $50 - ON SALE!!!!
Contact: unitycoderz2022@gmail.com
=========================================================
Script:
CountdownTimer.cs
using UnityEngine;
using UnityEngine.UI; // Import this if you want to display the timer in the UI.
public class CountdownTimer : MonoBehaviour
{
public float targetTimeInHours; // Public float to set countdown time in hours
private float timeRemaining;
private bool timerIsRunning = false;
// For displaying the time
public Text timerText; // Assign this in the Inspector if using UI
// Public function to start the timer
public void StartTimer()
{
// Convert target time from hours to seconds
timeRemaining = targetTimeInHours * 3600; // 1 hour = 3600 seconds
timerIsRunning = true;
}
private void Update()
{
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime; // Decrease the timer
UpdateTimerDisplay();
}
else
{
timeRemaining = 0;
timerIsRunning = false;
TimerFinished();
}
}
}
private void UpdateTimerDisplay()
{
// Convert timeRemaining to hours, minutes, seconds
int hours = Mathf.FloorToInt(timeRemaining / 3600);
int minutes = Mathf.FloorToInt((timeRemaining % 3600) / 60);
int seconds = Mathf.FloorToInt(timeRemaining % 60);
// Format the time string
string timeString = string.Format("{0:D2}:{1:D2}:{2:D2}", hours, minutes, seconds);
// Update the UI text if assigned
if (timerText != null)
{
timerText.text = timeString;
}
}
private void TimerFinished()
{
// Actions to take when the timer finishes
Debug.Log("Timer finished!");
// Add any additional logic here
}
}