A useful Countdown Timer Class in C#

The CountdownTimer is a versatile utility class designed for free use in your Unity project. This class provides an elegant solution for managing countdowns and timing events in your games or applications.

In today’s blog post, I’m excited to introduce the CountdownTimer, a versatile utility class designed for free use in your Unity project. This class provides an elegant solution for managing countdowns and timing events in your games or applications.

It supports essential functionalities such as starting, restarting, and checking the timer’s status or the percentage of time remaining. Whether you need to enforce time limits, create countdown mechanics, or track elapsed time for any purpose, the CountdownTimer is crafted to be a robust and straightforward component you can easily integrate into your Unity projects.

Let’s delve into how this class operates and how it can enhance the timing-related aspects of your development endeavors.

using UnityEngine;

/// <summary>
/// A Timer component that can be used to track time for in-game events.
/// This timer supports pause/resume functionality if it's designated as an in-game timer.
/// </summary>
public class CountdownTimer : MonoBehaviour
{
    [Tooltip("The total duration of the timer in seconds.")]
    public float duration;

    [Tooltip("The current remaining duration of the timer in seconds.")]
    public float currentDuration;

    /// <summary>
    /// Updates the timer's current duration each frame
    /// </summary>
    private void Update()
    {
        // Decrease the current duration based on the elapsed time since the last frame.
        currentDuration -= Time.deltaTime;
    }

    /// <summary>
    /// Starts or restarts the timer with the duration specified in the 'duration' field.
    /// </summary>
    public void StartTimer()
    {
        currentDuration = duration;
    }

    /// <summary>
    /// Checks if the timer has completed its countdown.
    /// </summary>
    /// <returns>True if the timer's current duration is less than zero; otherwise, false.</returns>
    public bool IsReady()
    {
        return currentDuration < 0;
    }

    /// <summary>
    /// Checks if the timer is currently running.
    /// </summary>
    /// <returns>True if the timer's current duration is non-negative; otherwise, false.</returns>
    public bool IsRunning()
    {
        return !IsReady();
    }

    /// <summary>
    /// The remaining ratio of the timer as a float between 0.0 and 1.0.
    /// </summary>
    /// <returns>The remaining ratio of the timer as a float value between 0.0 and 1.0. 1.0 means the timer just started, 0.0 means the countdown has finished.</returns>
    public float PercentRemaining()
    {
        // Ensure we don't divide by zero in case duration is not set or set to zero.
        if (duration <= 0) return 0.0;
        return currentDuration / duration;
    }
}