Menu
CoddyTech

Canvas and Text

Part of the Building Real Games section of Coddy's Unity journey. Lesson 1 of 60.

Unity draws on-screen text, buttons and bars with its UI system. In Unity 6, GameObject > UI > Text - TextMeshPro adds a text object named Text (TMP); the first time, Unity asks to import the TMP Essentials, which the text needs for its font. If the scene has no Canvas yet, Unity makes one and puts the text inside it, plus an EventSystem that UI clicks go through. The Canvas draws its children over the camera's picture, at a fixed place on the screen wherever the camera looks. Set its Canvas Scaler to Scale With Screen Size, 1920 x 1080, Match 0.5, as every scene in this course does, and the layout keeps its proportions on any screen size.

The text's component is TextMeshPro - Text (UI). Scripts hold it in a field of its base type TMP_Text, from the TMPro namespace, and change what it shows through its text property, a string. This script names the level when it starts:

using UnityEngine;
using TMPro;

public class LevelIntro : MonoBehaviour
{
    public TMP_Text titleText;

    void Start()
    {
        titleText.text = "World 2: Ice Caves";
    }
}

Drag the Text (TMP) object from the Hierarchy into the Title Text slot in the Inspector, and Unity puts its text component in the field. Without using TMPro; the name TMP_Text is unknown and the script does not compile (CS0246). With the slot left empty, the first titleText.text throws UnassignedReferenceException. What the script writes replaces the Text Input typed in the Inspector, which is New Text on a fresh text.

challenge icon

Challenge

Easy

Show which zone the explorer is in, in the ZoneText at the top.

  1. In Explorer.cs, add using TMPro; and the field public TMP_Text zoneText;. The scene links ZoneText to that name.
  2. In Update(), below the comment, set zoneText.text to Zone: Beach while transform.position.x is below 2, and to Zone: Jungle otherwise.

Press Play and walk right onto the grass: the text turns to Jungle. Then Check.

Try it yourself

using UnityEngine;

public class Explorer : MonoBehaviour
{
    public float speed = 4f;

    void Update()
    {
        float move = Input.GetAxisRaw("Horizontal");
        transform.Translate(move * speed * Time.deltaTime, 0f, 0f);

        // Show the zone in the ZoneText: Zone: Beach below x = 2, Zone: Jungle from 2 on
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground