Stay on track with this easy-to-implement timer that’s perfect for games and other applications!
Unity Quick Tips: Creating a Simple Timer
Part 5 of Our Bite-Sized Unity Tips and Tricks for Beginners
--
Welcome to Part 5 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to create a simple timer in Unity. Whether you’re creating a game or another application, a timer is a great way to keep track of time and add some structure to your scene.
Here’s the code sample:
using UnityEngine;
public class Timer : MonoBehaviour
{
public float time = 30f;
private void Update()
{
time -= Time.deltaTime;
if (time <= 0f)
{
Debug.Log("Time's up!");
}
}
}
In this script, we use the Update
function to continuously update the time remaining. First, we declare a public float
variable time
to represent the time remaining. Then, in the Update
function, we subtract Time.deltaTime
from the time
variable. This gives us the time remaining after each frame. Finally, we add a check to see if the time
has reached zero, and if it has, we log a message to the console using the Debug.Log
method.
Here are a few ways you can optimize and enhance the script for creating a simple timer in Unity:
- Display the Time Remaining: You can display the time remaining on the screen by using the
GUI.Label
method to draw a label with the time remaining on the screen. - Add a Timer Complete Event: You can add a timer complete event that is triggered when the time reaches zero. This can be useful for triggering other events, such as game over or level complete.
- Add a Pause and Resume Functionality: You can add a pause and resume functionality to the timer by adding a public
bool
variable to control the state of the timer and adding a check in theUpdate
function to see if the timer is paused. - Add a Count-Up Timer: You can modify the script to create a count-up timer, rather than a count-down timer, by adding time to the
time
variable instead of subtracting it.