Introduction

How to Counter, Timer & Game Over Logic using C# Script in Unity 3D
Prerequisites
Unity Environment version 2018.4.25f1

Create the project

How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D

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.
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
Rename the Text as UITimer
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
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.
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
Rename the script as TimerGameOverLogic.
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
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:
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. public class TimerGameOverLogic: MonoBehaviour {
  7. int countDownStartValue = 120;
  8. public Text timerUI;
  9. void Start() {
  10. countDownTimer();
  11. }
  12. void countDownTimer() {
  13. if (countDownStartValue > 0) {
  14. TimeSpan spanTime = TimeSpan.FromSeconds(countDownStartValue);
  15. timerUI.text = "Timer : " + spanTime.Minutes + " : " + spanTime.Seconds;
  16. countDownStartValue--;
  17. Invoke("countDownTimer", 1.0 f);
  18. } else {
  19. timerUI.text = "GameOver!";
  20. }
  21. }
  22. void Update() {}
  23. }

Save the Program

Drag and drop the TimerGameOverLogic script onto the UITimer
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
Drag and drop the UITimer onto the TimerGameOverLogic script.
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D
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.
How To Counter, Timer And Game Over Logic Using C# Script In Unity 3D

Summary

I hope you understood how to Counter, Timer & Game Over Logic using C# Script in Unity 3D.