Building A TimerUnderstanding time.deltaTime in Unity

Author Waldo
Published July 20, 2018

In this tutorial I explain how time.deltaTime works and how we can use it to build a stopwatch and a countdown timer. 

Video Walkthrough

  • 0:30 Creating a Text Field
  • 1:10 Adding a Custom Google Font
  • 1:40 Creating a Countdown Script
  • 2:45 Explaining time.deltaTime
  • 4:40 Creating a Stopwatch Script
  • 5:45 Using a UI button to start/stop timer
  • 7:05 Changing our buttons text on the fly

Source Code for Countdown.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Countdown : MonoBehaviour {
    public float timeStart = 60;
    public Text textBox;

	// Use this for initialization
	void Start () {
        textBox.text = timeStart.ToString();
	}
	
	// Update is called once per frame
	void Update () {
        timeStart -= Time.deltaTime;
        textBox.text = Mathf.Round(timeStart).ToString();
	}
}

Source Code for StopWatch.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class StopWatch : MonoBehaviour {
    public float timeStart;
    public Text textBox;
    public Text startBtnText;

    bool timerActive = false;

	// Use this for initialization
	void Start () {
        textBox.text = timeStart.ToString("F2");
	}
	
	// Update is called once per frame
	void Update () {
        if(timerActive){
            timeStart += Time.deltaTime;
            textBox.text = timeStart.ToString("F2");
        }
	}
    public void timerButton(){
        timerActive = !timerActive;
        startBtnText.text = timerActive ? "Pause" : "Start";
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About