Game Controller

Checked with version: 5.1

-

Difficulty: Beginner

Write a controller to spawn our hazards, keep track of and display our score, end the game and allow the game to be restarted.

Game Controller

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.

GameController

Code snippet

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour
{
    public GameObject hazard;
    public Vector3 spawnValues;

    void Start ()
    {
        SpawnWaves ();
    }

    void SpawnWaves ()
    {
        Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
        Quaternion spawnRotation = Quaternion.identity;
        Instantiate (hazard, spawnPosition, spawnRotation);
    }
}
var hazard : GameObject;
var spawnValues : Vector3;

function Start () {
    SpawnWaves ();
}

function SpawnWaves () {
    var spawnPosition : Vector3= new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
    var spawnRotation : Quaternion= Quaternion.identity;
    Instantiate (hazard, spawnPosition, spawnRotation);
}
import UnityEngine
import System.Collections


public class GameController(MonoBehaviour):

    public hazard as GameObject
    public spawnValues as Vector3
    
    private def Start():
        SpawnWaves()
    
    private def Update():
        if restart:
            if Input.GetKeyDown(KeyCode.R):
                Application.LoadLevel(Application.loadedLevel)
    
    private def SpawnWaves() as IEnumerator:
        spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z)
        spawnRotation as Quaternion = Quaternion.identity
        Instantiate(hazard, spawnPosition, spawnRotation)

Related tutorials

Related documentation