How to create a Timer with scripting (C#) in Unity 2018. Learn to start, stop and reset the timer using UI buttons in this Intermediate tutorial. Direct links to the free font and background below.


Subscribe to Oxmond Tutorials:
https://bit.ly/SubscribeOxmondTutorials

Download the Digital 7 font here:
https://www.dafont.com/digital-7.font

Timer background asset based on this file by Fabio Basile:
https://all-free-download.com/free-psd/download/timer-widget-interface-with-blue-digital-numbers_175188.html

Other Free Asset Packages at the Unity Assets Store:
https://assetstore.unity.com/lists/top-free-packages-13201

Asset Store links sponsored by Unity


Timer script:

/* .-------.                             .--.    .-------.     .--.            .--.     .--.        
   |       |--.--.--------.-----.-----.--|  |    |_     _|--.--|  |_.-----.----|__|---.-|  |-----.
   |   -   |_   _|        |  _  |     |  _  |      |   | |  |  |   _|  _  |   _|  |  _  |  |__ --|
   |_______|__.__|__|__|__|_____|__|__|_____|      |___| |_____|____|_____|__| |__|___._|__|_____|
   © OXMOND / www.oxmond.com */

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

public class Timer : MonoBehaviour {

    public Text timerMinutes;
    public Text timerSeconds;
    public Text timerSeconds100;

    private float startTime;
    private float stopTime;
    private float timerTime;
    private bool isRunning = false;

	// Use this for initialization
	void Start () {
        TimerReset();
    }

    public void TimerStart() {
        if (!isRunning) {
            print("START");
            isRunning = true;
            startTime = Time.time;       
        }
    }

    public void TimerStop()
    {
        if (isRunning)
        {
            print("STOP");
            isRunning = false;
            stopTime = timerTime;
        }
    }

    public void TimerReset()
    {
        print("RESET");
        stopTime = 0;
        isRunning = false;
        timerMinutes.text = timerSeconds.text = timerSeconds100.text = "00";
    }

    // Update is called once per frame
    void Update () {
        timerTime = stopTime + (Time.time - startTime);
        int minutesInt = (int)timerTime / 60;
        int secondsInt = (int)timerTime % 60;
        int seconds100Int = (int)(Mathf.Floor((timerTime - (secondsInt + minutesInt * 60)) * 100));

        if (isRunning)
        {
            timerMinutes.text = (minutesInt < 10) ? "0" + minutesInt : minutesInt.ToString();
            timerSeconds.text = (secondsInt < 10) ? "0" + secondsInt : secondsInt.ToString();
            timerSeconds100.text = (seconds100Int < 10) ? "0" + seconds100Int : seconds100Int.ToString();
        }
    }
}