Ending the game

Checked with version: 5.1

-

Difficulty: Beginner

End the game and show the state of the game with labels for Game Over and Restart.

Ending the game

Beginner Space Shooter tutorial

Please note that this project was developed for Unity version 4. It currently works, and has been checked, with Unity version 5.1. Please turn annotations on while watching the video, as we can add annotations to the videos when there are discrepancies between the recorded content and the current version of Unity.

Get the Upgrade Guide for Unity 5 here.

Please refer to the Official Q&A Page on the Forums for an Upgrade FAQ and to ask any questions.

DestroyByContact

Code snippet

using UnityEngine;
using System.Collections;

public class DestroyByContact : MonoBehaviour
{
    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    private GameController gameController;

    void Start ()
    {
        GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent <GameController>();
        }
        if (gameController == null)
        {
            Debug.Log ("Cannot find 'GameController' script");
        }
    }

    void OnTriggerEnter(Collider other) 
    {
        if (other.tag == "Boundary")
        {
            return;
        }
        Instantiate(explosion, transform.position, transform.rotation);
        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver ();
        }
        gameController.AddScore (scoreValue);
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}
var explosion : GameObject;
var playerExplosion : GameObject;
var scoreValue : int;
private var gameController : GameController;

function Start ()
{
    var gameControllerObject : GameObject = GameObject.FindWithTag ("GameController");
    if (gameControllerObject != null)
    {
        gameController = gameControllerObject.GetComponent (GameController);
    }
    if (gameController == null)
    {
        Debug.Log ("Cannot find 'GameController' script");
    }
}

function OnTriggerEnter(other : Collider) 
{
    if (other.tag == "Boundary")
    {
        return;
    }
    Instantiate(explosion, transform.position, transform.rotation);
    if (other.tag == "Player")
    {
        Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
        gameController.GameOver ();
    }
    gameController.AddScore (scoreValue);
    Destroy(other.gameObject);
    Destroy(gameObject);
}
import UnityEngine
import System.Collections

public class DestroyByContact(MonoBehaviour):
    public explosion as GameObject
    public playerExplosion as GameObject
    public scoreValue as int
    private gameController as GameController
    
    private def Start():
        gameControllerObject as GameObject = GameObject.FindWithTag('GameController')
        if gameControllerObject is not null:
            gameController = gameControllerObject.GetComponent[of GameController]()
        if gameController is null:
            Debug.Log('Cannot find \'GameController\' script')

    private def OnTriggerEnter(other as Collider):
        if other.tag == 'Boundary':
            return
        Instantiate(explosion, transform.position, transform.rotation)
        if other.tag == 'Player':
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation)
            gameController.GameOver()
        gameController.AddScore(scoreValue)
        Destroy(other.gameObject)
        Destroy(gameObject)

GameController

Code snippet

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour
{
    public GameObject hazard;
    public Vector3 spawnValues;
    public int hazardCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    public GUIText scoreText;
    public GUIText restartText;
    public GUIText gameOverText;

    private bool gameOver;
    private bool restart;
    private int score;

    void Start ()
    {
        gameOver = false;
        restart = false;
        restartText.text = "";
        gameOverText.text = "";
        score = 0;
        UpdateScore ();
        StartCoroutine (SpawnWaves ());
    }

    void Update ()
    {
        if (restart)
        {
            if (Input.GetKeyDown (KeyCode.R))
            {
                Application.LoadLevel (Application.loadedLevel);
            }
        }
    }

    IEnumerator SpawnWaves ()
    {
        yield return new WaitForSeconds (startWait);
        while (true)
        {
            for (int i = 0; i < hazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate (hazard, spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
            yield return new WaitForSeconds (waveWait);

            if (gameOver)
            {
                restartText.text = "Press 'R' for Restart";
                restart = true;
                break;
            }
        }
    }

    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore ();
    }

    void UpdateScore ()
    {
        scoreText.text = "Score: " + score;
    }

    public void GameOver ()
    {
        gameOverText.text = "Game Over!";
        gameOver = true;
    }
}
var hazard : GameObject;
var spawnValues : Vector3;
var hazardCount : int;
var spawnWait : float;
var startWait : float;
var waveWait : float;

var scoreText : GUIText;
var restartText : GUIText;
var gameOverText : GUIText;

private  var gameOver : boolean;
private  var restart : boolean;
private  var score : int;

function Start () {
    gameOver = false;
    restart = false;
    restartText.text = "";
    gameOverText.text = "";
    score = 0;
    UpdateScore ();
    StartCoroutine (SpawnWaves ());
}

function Update () {
    if (restart)
    {
        if (Input.GetKeyDown (KeyCode.R))
        {
            Application.LoadLevel (Application.loadedLevel);
        }
    }
}

function SpawnWaves () {
    yield WaitForSeconds (startWait);
    while (true)
    {
        for ( var i : int= 0; i < hazardCount; i++)
        {
             var spawnPosition : Vector3= new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
             var spawnRotation : Quaternion= Quaternion.identity;
            Instantiate (hazard, spawnPosition, spawnRotation);
            yield WaitForSeconds (spawnWait);
        }
        yield WaitForSeconds (waveWait);

        if (gameOver)
        {
            restartText.text = "Press 'R' for Restart";
            restart = true;
            break;
        }
    }
}

function AddScore (newScoreValue : int) {
    score += newScoreValue;
    UpdateScore ();
}

function UpdateScore () {
    scoreText.text = "Score: " + score;
}

function GameOver () {
    gameOverText.text = "Game Over!";
    gameOver = true;
}
import UnityEngine
import System.Collections

public class GameController(MonoBehaviour):

    public hazard as GameObject
    public spawnValues as Vector3
    public hazardCount as int
    public spawnWait as single
    public startWait as single
    public waveWait as single

    public scoreText as GUIText
    public restartText as GUIText
    public gameOverText as GUIText
    
    private gameOver as bool
    private restart as bool
    private score as int
    
    private def Start():
        gameOver = false
        restart = false
        restartText.text = ''
        gameOverText.text = ''
        score = 0
        UpdateScore()
        StartCoroutine(SpawnWaves())
    
    private def Update():
        if restart:
            if Input.GetKeyDown(KeyCode.R):
                Application.LoadLevel(Application.loadedLevel)
    
    private def SpawnWaves() as IEnumerator:
        yield WaitForSeconds(startWait)
        while true:
            for i in range(0, hazardCount):
                spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z)
                spawnRotation as Quaternion = Quaternion.identity
                Instantiate(hazard, spawnPosition, spawnRotation)
                yield WaitForSeconds(spawnWait)
            yield WaitForSeconds(waveWait)
            
            if gameOver:
                restartText.text = 'Press \'R\' for Restart'
                restart = true
                break 
    
    public def AddScore(newScoreValue as int):
        score += newScoreValue
        UpdateScore()
    
    private def UpdateScore():
        scoreText.text = ('Score: ' + score)
    
    public def GameOver():
        gameOverText.text = 'Game Over!'
        gameOver = true

Related documentation