Sunday, January 2, 2022

Stopwatch Timer in Unity

 Stopwatch Timer in Unity



Hello friends two we will se how we can add stopwatch in our scene. we can use this for time based game-over game as well.

So lets move to the script :

TimerGame.cs

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

public class TimerGame : MonoBehaviour
{
    int timerstart = 120;
    public Text Timertext;
    private void Start()
    {
        countdown_Timer();
    }
    void countdown_Timer()
    {
        if (timerstart > 0)
        {
            TimeSpan spanTime = TimeSpan.FromSeconds(timerstart);
            Timertext.text = "Timer : " + spanTime.Minutes +" : "+ spanTime.Seconds;
            timerstart--;
            Invoke("countdown_Timer", 1.0f);
        }
        else
        {
            Timertext.text = "Game Over!";
        }
    }
}

attach this script to your camera.

Add UI Text to you game scene.

Right click in hierarchy -> canvas -> text.

Place textbox at center of canvas.




Now Run your game scene. and see the text box there you will see the stopwatch like below.




See the Video :








0 Comments:

Post a Comment

Thank you for your comment !