pageTitleCS

 timerTitle

Adding a countdown timer to your game levels add another dimension to your game play. Below we will look at adding a simple countdown timer which loads another scene when the timer reaches 0.

Step 1:
Create a canvas and add a UI text element. This is used to display the timer on sceen.

Step2:
Create a new script called timer and add the script below.

JS

#pragma strict

static var startTime : int;
var textTime : String;
var timeAllowedSec : float;
// drag the UI text element into this variable in the inspector
var timerDisplayText : UI.Text;
//added this variable as static so we can access it through other scripts
static var guiTime : float;


function Awake() {
startTime = timeAllowedSec + Time.time;
}

function Update() {
guiTime = startTime - Time.time;
var minutes : int = guiTime/60;

if(guiTime < 60){
minutes = 0;
}

if(startTime < 60){
minutes = 0;
}

var seconds : int = guiTime % 60;
textTime = String.Format ("{0:00}:{1:00}", minutes, seconds);
timerDisplayText.text = textTime;

if(guiTime < 0){
// Add what ever code you want to be executed at no time remaining in here
Application.LoadLevel(2);
}

}

C#

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

public class timer : MonoBehaviour {

float startTime;
public float timeAllowedSec;
string textTime;
// drag the UI text element into this variable in the inspector
public Text timerDisplayText;
//added this variable as public so we can access it through other scripts
float guiTime;

// Use this for initialization
void Awake () {
startTime = timeAllowedSec + Time.time;
}

// Update is called once per frame
void Update () {
guiTime = startTime - Time.time;
float minutes = guiTime/60;

if(guiTime < 60){
minutes = 0;
}

if(startTime < 60){
minutes = 0;
}

float seconds = guiTime % 60;
textTime = string.Format ("{0:00}:{1:00}", minutes, seconds);
timerDisplayText.text = textTime;

if(guiTime < 0){
// Add what ever code you want to be executed at no time remaining in here
Application.LoadLevel(2);
}

}
}

Step 3:
Attach the script to a game object in your scene and attach the UI.text element in the inspector. 

Casino Bet 365 is best casino in the world.

What's Next

Next up for Unity Snippets is a look at game development articles from across the web...

Free Templates - bigtheme.net
Popular Art Betting make bookies articles.