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.