Unity's user interface (UI) allows you to add and position the text using a
Previously, Unity used a basic text system for UI. However, with advancements, a new text system called the TextMeshPro was introduced. TextMeshPro is a powerful and flexible solution for text rendering in Unity. It offers advanced text layout and markup options, improved performance, and better text visual customization capabilities.
Given below are the steps on how to add, position, and change the text on canvas in Unity.
Right click in the Hierarchy window and click on UI > Text - TextMeshPro.
This will create a canvas GameObject in the scene with a child.
Adjust the text object's position either by:
Move tool in the scene view
Transform component in the inspector pane
Navigate to the TextMeshPro component in the inspector pane
Edit the "Text" field with the desired content
Create a new C# script
A sample C# script is given below.
using System.Collections;using System.Collections.Generic;using UnityEngine;using TMPro;public class Modify_text : MonoBehaviour{public TMP_Text canvasText;// Start is called before the first frame updatevoid Start(){canvasText.text = "Hi, it's me!";}}
Lines 1–3: These lines make the necessary imports.
Line 4: It includes the TextMeshPro namespace to allow access to the TextMeshPro related classes and functions.
Line 6: A class is declared named Modify_text
. It inherits methods from the class MonoBehaviour
, a base class in Unity for the scripts attached to the specific GameObjects.
Line 8: It declares a public variable named canvasText
which is of type TMP_text
. The variable holds a reference to the TextMeshPro text object which you can modify.
Lines 10–13: The Start()
method is a callback method which is automatically invoked before the first frame update. It is generally used for initialization. CanvasText.text
sets the text of the TextMeshPro object (referenced by the CanvasText
variable).
Create an empty GameObject in the hierarchy tab.
Select the GameObject
Drag and drop the C# script in the inspector pane
Drag the TextMeshPro text from the hierarchy into the Canvas_Text
field in the Modify_text
script component.
Enter the game mode
Your text should show the content specified in the C# script
Free Resources