Link Search Menu Expand Document

Heads-Up Display (HUD)

A HUD is an overlay in a Scene where you can add information relevant to the player like health, score, and lives Wikipedia. We are going to add one to our game so we can display a score to the player.

Add a Canvas

In Unity, a Canvas is a GameObject that allows you to add HUD components like overlaid text.

In the Hierarchy, right-click on your SampleScene add navigate to GameObject > UI > Canvas. Any UI components can be added as children to this Canvas.

Add Canvas

Add Text objects for a score

Add two Text UI GameObjects to the Canvas (GameObject > UI > Text) and name them “ScoreLabel” and “Score”.

Add Canvas Children

Score

The “Score” text object will be used to display the numeric score value that changes when the player performs actions in the game. In the Inspector, set the Text to 0.

Score

ScoreLabel

The ScoreLabel’s job will be to just display the text Score:. Place the label to the left of your Score in the Canvas so that together, they read Score: 0. Don’t be alarmed that the Canvas is so big relative to the Main Camera in the Scene view, it will look fine when you press play.

Score Label

Game with HUD

At this point your game should look something like this when you press “play”.

Game w/HUD

Score Script

We need to add a script to our Score GameObject to make sure that the score is reset every time we start the game. Call it Score.

using UnityEngine;

public class Score : MonoBehaviour
{
    // Reset the score at the start of the game
    void Start()
    {
        // if it's the zeroth scene (buildIndex == 0)
        if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex == 0)
        {
            // reset the score
            PlayerPrefs.SetInt("score", 0);
        }
        GetComponent<UnityEngine.UI.Text>().text = PlayerPrefs.GetInt("score").ToString();
    }
}

NOTE: If you use TextMeshPro instead of the legacy Text option, you should use this code instead:

- GetComponent<UnityEngine.UI.Text>().text = PlayerPrefs.GetInt("score").ToString();
+ GetComponent<TMPro.TextMeshProUGUI>().text = PlayerPrefs.GetInt("score").ToString();