Timer / Countdown

Versatile timer with countdown, stopwatch, and repeating modes. Formatted time display and UnityEvent callbacks.

File
Timer.cs
Unity
2022.3+
Level
beginner
Size
2.1 KB · 117 lines
Added
2026-03-08
License
MIT
View source

No APIs that Unity 6.0 to 6.6 made obsolete or removed. How this is checked

What it adds to your GameObject

A MonoBehaviour component: attach it to a GameObject. This is the Inspector you get, read from the source: 7 serialized fields with their defaults.

Inspector
Script Timer
Settings
Mode Countdown
Duration 60
Start On Awake
Use Unscaled Time
Events
On Timer Start ()
List is Empty
On Timer Complete ()
List is Empty
On Timer Tick (float)
List is Empty

When to use it

Essential for puzzle games with time limits, racing games with lap timers, survival games with day/night cycles, and wave-based games with spawn intervals. Use the Repeating mode for periodic events like health regeneration ticks or spawner cooldowns. The Stopwatch mode is great for speedrun timers or play-time tracking.

Setup

  1. Attach Timer to any GameObject
  2. Choose mode: Countdown (default), Stopwatch, or Repeating
  3. Set duration in inspector (in seconds)
  4. Connect OnTimerComplete event to trigger actions
  5. Display: timer.FormattedTime gives 'MM:SS' string
  6. Control: StartTimer(), Pause(), Resume(), Stop()

Features

  • Three modes: Countdown, Stopwatch, and Repeating timer
  • Formatted time string property (MM:SS) for direct UI display
  • Normalized progress (0-1) for driving sliders and fill bars
  • UnityEvent callbacks for start, tick, and completion
  • Unscaled time option for timers that work during pause menus
  • Runtime SetDuration method for dynamic timer adjustments

Inspector fields

Every field Timer / Countdown exposes in the Inspector, with the default it starts at.

FieldTypeDefaultGroup
ModemodeTimerModeCountdownSettings
Durationdurationfloat60Settings
Start On AwakestartOnAwakeboolfalseSettings
Use Unscaled TimeuseUnscaledTimeboolfalseSettings
On Timer StartOnTimerStartUnityEventNo listenersEvents
On Timer CompleteOnTimerCompleteUnityEventNo listenersEvents
On Timer TickOnTimerTickUnityEvent<float>No listenersEvents

Public API

What other scripts can call on Timer.

MemberReturnsDescription
StartTimer()voidStart or restart the timer.
Pause()voidPause the timer.
Resume()voidResume the timer.
Stop()voidStop and reset the timer.
SetDuration(float newDuration)voidSet a new duration at runtime.
CurrentTime propertyfloatCurrent time in seconds.
IsRunning propertyboolIs the timer currently running?
Progress propertyfloatNormalized progress (0 to 1).

Common mistakes

If startOnAwake is false (the default), the timer won't start until you call StartTimer() — it's easy to forget this and wonder why nothing happens. The OnTimerTick event sends a normalized 0-1 value, not the raw seconds remaining — use CurrentTime if you need actual seconds. In Repeating mode, the timer resets to duration after each complete cycle, so OnTimerComplete fires repeatedly.

Source code

Timer.cs, 117 lines, MIT licensed. Paste it into a new C# file of the same name.

Timer.cs
C#
using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// Versatile timer supporting countdown, stopwatch, and repeating modes.
/// Provides formatted time display and event callbacks.
/// </summary>
public class Timer : MonoBehaviour
{
    public enum TimerMode { Countdown, Stopwatch, Repeating }

    [Header("Settings")]
    [SerializeField] private TimerMode mode = TimerMode.Countdown;
    [SerializeField] private float duration = 60f;
    [SerializeField] private bool startOnAwake = false;
    [SerializeField] private bool useUnscaledTime = false;

    [Header("Events")]
    public UnityEvent OnTimerStart;
    public UnityEvent OnTimerComplete;
    public UnityEvent<float> OnTimerTick; // normalized 0-1

    private float currentTime;
    private bool isRunning;

    /// <summary>Current time in seconds.</summary>
    public float CurrentTime => currentTime;

    /// <summary>Is the timer currently running?</summary>
    public bool IsRunning => isRunning;

    /// <summary>Normalized progress (0 to 1).</summary>
    public float Progress => mode == TimerMode.Stopwatch
        ? (duration > 0f ? Mathf.Clamp01(currentTime / duration) : 0f)
        : (duration > 0f ? Mathf.Clamp01(1f - currentTime / duration) : 0f);

    /// <summary>Formatted time string (MM:SS).</summary>
    public string FormattedTime
    {
        get
        {
            float t = mode == TimerMode.Stopwatch ? currentTime : Mathf.Max(0f, currentTime);
            int minutes = Mathf.FloorToInt(t / 60f);
            int seconds = Mathf.FloorToInt(t % 60f);
            return string.Format("{0:00}:{1:00}", minutes, seconds);
        }
    }

    private void Start()
    {
        if (startOnAwake)
            StartTimer();
    }

    private void Update()
    {
        if (!isRunning) return;

        float dt = useUnscaledTime ? Time.unscaledDeltaTime : Time.deltaTime;

        switch (mode)
        {
            case TimerMode.Countdown:
                currentTime -= dt;
                OnTimerTick?.Invoke(Progress);
                if (currentTime <= 0f)
                {
                    currentTime = 0f;
                    isRunning = false;
                    OnTimerComplete?.Invoke();
                }
                break;

            case TimerMode.Stopwatch:
                currentTime += dt;
                OnTimerTick?.Invoke(Progress);
                break;

            case TimerMode.Repeating:
                currentTime -= dt;
                OnTimerTick?.Invoke(Progress);
                if (currentTime <= 0f)
                {
                    OnTimerComplete?.Invoke();
                    currentTime = duration;
                }
                break;
        }
    }

    /// <summary>Start or restart the timer.</summary>
    public void StartTimer()
    {
        currentTime = (mode == TimerMode.Stopwatch) ? 0f : duration;
        isRunning = true;
        OnTimerStart?.Invoke();
    }

    /// <summary>Pause the timer.</summary>
    public void Pause() => isRunning = false;

    /// <summary>Resume the timer.</summary>
    public void Resume() => isRunning = true;

    /// <summary>Stop and reset the timer.</summary>
    public void Stop()
    {
        isRunning = false;
        currentTime = (mode == TimerMode.Stopwatch) ? 0f : duration;
    }

    /// <summary>Set a new duration at runtime.</summary>
    public void SetDuration(float newDuration)
    {
        duration = newDuration;
    }
}