How to Create a Timer or Stopwatch in Unity

How to Create a Timer or Stopwatch in Unity

Timers and stopwatches are essential tools for many games, and Unity makes it easy to create them. In this tutorial, we will show you how to create a simple timer or stopwatch in Unity.

Steps to follow:

  1. Create a new Unity project.
  2. Create a text object in the hierarchy.
  3. Create a new script called Timer and attach it to the text object.
  4. In the Timer script, create two public variables: timeRemaining and timeIsRunning.
  5. The timeRemaining variable will store the amount of time remaining on the timer, and the timeIsRunning variable will be a boolean that determines whether the timer is running or not.
  6. Create an Update function in the Timer script.
  7. In the Update function, check if the timeIsRunning variable is true and if the timeRemaining variable is greater than zero.
  8. If both of these conditions are true, subtract the time elapsed since the last frame from the timeRemaining variable.
  9. Create a displayTime function in the Timer script.
  10. In the displayTime function, calculate the minutes and seconds for the timer.
  11. Update the text object with the current time.
  12. Drag and drop the Timer script into the time attack and add the text from the hierarchy.

Here is the code for the Timer script:

C#
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    public float timeRemaining = 10;
    public bool timeIsRunning = false;
    public Text timerText;

    void Update()
    {
        if (timeIsRunning && timeRemaining > 0)
        {
            timeRemaining -= Time.deltaTime;
            displayTime();
        }
    }

    void displayTime()
    {
        int minutes = Mathf.FloorToInt(timeRemaining / 60);
        int seconds = Mathf.FloorToInt(timeRemaining % 60);
        timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

Here is the code for the StartTimer function:

C#
public void StartTimer()
{
    timeIsRunning = true;
}

Here is the code for the StopTimer function:

C#
public void StopTimer()
{
    timeIsRunning = false;
}

Here is the code for the ResetTimer function:

C#
public void ResetTimer()
{
    timeRemaining = 10;
    timeIsRunning = false;
}

You can now use the StartTimer, StopTimer, and ResetTimer functions to start, stop, and reset the timer.

Here are some additional tips:

  • You can change the initial value of the timeRemaining variable to set the duration of the timer.
  • You can add a button to start and stop the timer.
  • You can add a sound effect to play when the timer runs out.
  • You can add a visual effect to indicate that the timer is running out.

I hope this tutorial helps you create a timer or stopwatch in Unity.

Comments