Session 4

 

Displaying the score

To display our score, we’re going to create a text object.  Unity has a system called “Canvas” which can display user interface (UI) objects, such as text and menus with buttons.

Go to Create in the Hierarchy Window, and select UI, then Text.  This will create three objects: The Canvas, a Text object parented to it, and an EventSystem object that catches button clicks.

We’re going to need two TextObjects, one for the score, and one for the GameOver text.

We’re going to create a GameManager object to track a few things throughout, starting with the score and the game over text. Create a new component, and rename it to “GameManager”. Then click Add Component, New Script, and then type “GameManager” as the name. In the script, replace everything with the following:

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

public class GameManager : MonoBehaviour {

    int score; 
     public Text ScoreText;
     public Text GameOverText;

    public string YouLose = "You lose!";
     public string YouWin = "You win!";

    // Use this for initialization
     void Start () {
         UpdateScore();
         GameOverText.text = "";
     }
     
     // Update is called once per frame
     void Update () {
         
     }

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

     public void GameOver () {
         GameOverText.text = YouLose;
     }

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

When we go back to the Inspector in the Editor, we can drag and add the Text objects we made to their respective Score and GameOver Text slots.

Now that we have the GameManager and Score adding code set up, let’s add the following to the bullet script:

  public float bulletSpeed;
 
     GameManager Manager;
 
     // Use this for initialization
     void Start () {
         Manager = GameObject.Find("GameManager").GetComponent<GameManager>();
     } 

     void OnTriggerEnter (Collider other) {
         if (other.CompareTag("enemy")) {
             Destroy(other.gameObject);
             Destroy(this.gameObject);
             Manager.AddScore();
         }
     }

On the ship.cs script, we’re going to add a few similar elements:

 GameManager Manager;
 
     // Use this for initialization
     void Start () {
         Manager = GameObject.Find("GameManager").GetComponent<GameManager>();
     } 

     void OnTriggerEnter (Collider other) {
         if (other.CompareTag("enemy")) {
             Destroy(other.gameObject);
             Destroy(this.gameObject);
             Manager.GameOver();
         }
     }

GameObject.Find(“name”) is a very computer heavy task, so it’s best to do it once when the script is activated the first time, and at the beginning of the scene if possible.