Building A TimerUnderstanding time.deltaTime in Unity

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

In this video you will learn:

  • 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";
    }
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION