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

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.   
  7. public class TimerGameOverLogic: MonoBehaviour {  
  8.   int countDownStartValue = 120;  
  9.   public Text timerUI;  
  10.   
  11.   void Start() {  
  12.     countDownTimer();  
  13.   }  
  14.   
  15.   void countDownTimer() {  
  16.     if (countDownStartValue > 0) {  
  17.       TimeSpan spanTime = TimeSpan.FromSeconds(countDownStartValue);  
  18.       timerUI.text = "Timer : " + spanTime.Minutes + " : " + spanTime.Seconds;  
  19.       countDownStartValue--;  
  20.       Invoke("countDownTimer", 1.0 f);  
  21.     } else {  
  22.       timerUI.text = "GameOver!";  
  23.     }  
  24.   }  
  25.   void Update() {}  
  26. }  

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.


Similar Articles