Unity Change Text With Script | Unity Tutorial
In this Unity tutorial, you'll learn how to dynamically change text in your game using scripts. We'll cover both the legacy Text component and TextMesh Pro, showing you how to update text content during runtime. Perfect for enhancing UI elements and adding interactivity to your game!
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
Unity Projects - ON SALE!!!
1. Water Sort Puzzle 9000 Levels
2. Ball Sort Puzzle 9000 Levels
3. Sling Shot
=========================================================
Legacy Script:
using UnityEngine;
using UnityEngine.UI; // Include this to access the UI components
public class TextUpdater : MonoBehaviour
{
public Text textComponent; // Reference to the Text component
void Start()
{
// Ensure the Text component is assigned in the Inspector
if (textComponent != null)
{
textComponent.text = "Hello, World!"; // Change the text
}
}
// Method to update text dynamically
public void UpdateText(string newText)
{
if (textComponent != null)
{
textComponent.text = newText;
}
}
}
TMP Script:
using UnityEngine;
using TMPro; // Include this to access TextMeshPro components
public class TextMeshUpdater : MonoBehaviour
{
public TMP_Text textMeshProComponent; // Reference to the TextMeshPro component
void Start()
{
// Ensure the TextMeshPro component is assigned in the Inspector
if (textMeshProComponent != null)
{
textMeshProComponent.text = "Hello, World!"; // Change the text
}
}
// Method to update text dynamically
public void UpdateText(string newText)
{
if (textMeshProComponent != null)
{
textMeshProComponent.text = newText;
}
}
}