In this tutorial, we will learn how to change the text of the button during runtime using code.
Before we proceed with changing the text here is how you can add a new button
Go to the Hierarchy window.
Click on the + sign or the create button depending on your Unity version.
Select UI>Button.
If you are looking to change the button text in editor just select the button in Hierarchy window and click on the small arrow near it. It will expose the text element. Select the text element and you can change the characters from the inspector.
To access any UI element, you need to add the namespace “using UnityEngine.UI” to your code.
Since it’s a text element you need to create a variable of type Text. Now you can access the text on the button and change it on the go.
You can use the code sample below to change the text of your button.
You need to drag and drop your button’s text element to the public variable tex.
using UnityEngine;
using UnityEngine.UI;
public class Text_change : MonoBehaviour
{
public Text tex;
float timer=0;
void Update()
{
timer+=Time.deltaTime;
tex.text=timer.ToString();
}
}
If you want to find the button’s text element you can use GameObject.Find. If you have any other questions, you can leave it in the comment section below.