How to Use TextMeshPro in Unity: Simple Guide
To use
TextMeshPro in Unity, first import the TextMeshPro package via the Package Manager, then add a TextMeshProUGUI component to a UI GameObject or TextMeshPro component to a 3D object. You can customize text properties in the Inspector or control text content via scripts using the text property.Syntax
TextMeshPro uses two main components depending on context: TextMeshProUGUI for UI text and TextMeshPro for 3D text. You access and modify text content via the text property. You can also change font size, color, and style through properties or the Inspector.
csharp
using TMPro; using UnityEngine; public class Example : MonoBehaviour { public TextMeshProUGUI uiText; public TextMeshPro meshText; void Start() { uiText.text = "Hello UI Text!"; meshText.text = "Hello 3D Text!"; uiText.fontSize = 36; meshText.color = Color.cyan; } }
Example
This example shows how to update a UI TextMeshPro text from a script. Attach this script to a GameObject and assign a TextMeshProUGUI component in the Inspector.
csharp
using TMPro; using UnityEngine; public class TextUpdater : MonoBehaviour { public TextMeshProUGUI myText; void Start() { myText.text = "Welcome to TextMeshPro!"; } void Update() { myText.text = "Time: " + Time.time.ToString("F2"); } }
Output
The UI text updates every frame showing the elapsed time in seconds with two decimals.
Common Pitfalls
- For UI text, use
TextMeshProUGUIinstead ofTextMeshPro. - Always import TextMeshPro package via Package Manager before use.
- Remember to assign the TextMeshPro component reference in scripts to avoid null errors.
- Changing text in Update without optimization can hurt performance.
csharp
using TMPro; using UnityEngine; public class WrongUsage : MonoBehaviour { public TextMeshProUGUI uiText; void Start() { // Wrong: forgetting to assign uiText in Inspector causes null error uiText.text = "This will cause an error if uiText is null."; } } // Correct usage: // Assign uiText in Inspector or find it in Start() before using.
Quick Reference
Here is a quick cheat sheet for common TextMeshPro tasks:
| Task | Code Example |
|---|---|
| Set UI text | myText.text = "Hello!"; |
| Change font size | myText.fontSize = 24; |
| Change color | myText.color = Color.red; |
| Make text bold | myText.fontStyle = FontStyles.Bold; |
| Clear text | myText.text = ""; |
Key Takeaways
Import TextMeshPro package before using its components.
Use TextMeshProUGUI for UI elements and TextMeshPro for 3D text.
Modify text content via the text property in scripts.
Assign component references in Inspector to avoid null errors.
Avoid frequent text changes in Update without optimization.