Change Unity UI Text of a TextMeshPro (TMP) in C#

In this tutorial, I am going to show you how to change the Unity UI text of a TextMeshPro (TMP) in C# programming with the help of an example.

Let’s first create a public variable of TMP type where we will attach our Text object of TextMeshPro:

public TMP_Text mainText;

Then inside the start, use the following code to update the TMP Text:

mainText.text = "This is Updated Text";

or you can also do it like:

mainText.SetText("This is Updated Text");

Complete and final code

Below is the complete and final code for changing and setting a new text to the Unity UI Text of a TMP:

using TMPro;
using UnityEngine;

public class GameManager : MonoBehaviour
{
     public TMP_Text mainText;
     void Start()
    {
      // Updating the text of TMP
      mainText.SetText("This is Updated Text");
    }
 
}

Remember to drag and drop the object to the variable in the inspector:

Screenshot portion

You can also do the same thing without using the SetText() method as you can see below:

using TMPro;
using UnityEngine;

public class GameManager : MonoBehaviour
{
     public TMP_Text mainText;
     void Start()
    {
       // Updating the Text of TMP
       mainText.text = "This is Updated Text";
    }
 
}

Leave a Reply

Your email address will not be published. Required fields are marked *