Introduction
How to Counter, Timer & Game Over Logic using C# Script in Unity 3D
Prerequisites
Unity Environment version 2018.4.25f1
Create the project
Create the UI Text ( user interface ) in unity
First, add a UI Text if there is no canvas. It is created automatically. Then, click on the "GameObject" menu in the menu bar. Select UI and pick the "Text" option.
Rename the Text as UITimer
the logic with the game over in unity so first let me create a script first I am going to create a c-sharp script.
Create C# Script, Right-click on Assets. Select Create >> C# script.
Rename the script as TimerGameOverLogic.
Double click in Scene and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
-
- public class TimerGameOverLogic: MonoBehaviour {
- int countDownStartValue = 120;
- public Text timerUI;
-
- void Start() {
- countDownTimer();
- }
-
- void countDownTimer() {
- if (countDownStartValue > 0) {
- TimeSpan spanTime = TimeSpan.FromSeconds(countDownStartValue);
- timerUI.text = "Timer : " + spanTime.Minutes + " : " + spanTime.Seconds;
- countDownStartValue--;
- Invoke("countDownTimer", 1.0 f);
- } else {
- timerUI.text = "GameOver!";
- }
- }
- void Update() {}
- }
Save the Program
Drag and drop the TimerGameOverLogic script onto the UITimer
Drag and drop the UITimer onto the TimerGameOverLogic script.
Now if we play our game and press on the play button.
Will be two minutes less tested now you can see one minute 57 seconds 56 seconds 55 seconds so that's how you can create a timer and game over logic in unity.
Summary
I hope you understood how to Counter, Timer & Game Over Logic using C# Script in Unity 3D.