How To Make A Timer With Unity/C# In 5 Minutes

How To Make A Timer With Unity/C# In 5 Minutes
Mr. Unity Buddy's photo
Mr. Unity Buddy

Published on Apr 1, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Hey Buddies! Today let's make a simple Timer with Unity, In 5 mins. So Start with you projects!

Joke Of The Day

1_9edgsm2B2q5s21SnYB2QUQ.png

Making Timer (Design / Script)

image.png

  • Next make a C# script 'Timer'. Then,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //Since you use a 'Text'object, you can't do anything without this using this. 

public class Timer : MonoBehaviour
{
    public float timeRemaining = 10;
    public bool timerIsRunning = false;
    public Text timeText;


    private void Start()
    {
        // Starts the timer automatically
        timerIsRunning = true;
    }

    void Update()
    {
        if (timerIsRunning)
        {
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {


                timeRemaining = 1;
                timerIsRunning = false;
            }

        }
    }

    void DisplayTime(float timeToDisplay)
    {
        timeToDisplay += 1;

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }


}
  • That's it! If you want to do something when Time Is Over like Activating a Panel etc, do That like this,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
    public float timeRemaining = 10;
    public bool timerIsRunning = false;
    public Text timeText;
    public GameObject TimeOutPanel;


    private void Start()
    {
        // Starts the timer automatically
        timerIsRunning = true;
    }

    void Update()
    {
        if (timerIsRunning)
        {
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {

                TimeOutPanel.SetActive(true); // Activating TimeOut Panel
                timeRemaining = 1;
                timerIsRunning = false;
            }

        }
    }

    void DisplayTime(float timeToDisplay)
    {
        timeToDisplay += 1;

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }


}
  • So that's it. See you again!
 
Share this