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
EasyShow which zone the explorer is in, in the ZoneText at the top.
- In
Explorer.cs, addusing TMPro;and the fieldpublic TMP_Text zoneText;. The scene links ZoneText to that name. - In
Update(), below the comment, setzoneText.texttoZone: Beachwhiletransform.position.xis below2, and toZone: Jungleotherwise.
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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground