Human Friend
Human Friend

Reputation: 175

How to change text by script in Unity

I have a unity project with a text field and I want to change it to something else by clicking a button. Like javscript ids.

Can someone help me?

Upvotes: 8

Views: 73863

Answers (2)

shodev
shodev

Reputation: 111

Unity recently added TextMeshPro in version 2021.3 as a way to display text. This process is much the same, but the only thing is to include "using TMPro" (instead of UnityEngine.UI) and "TMP_Text" (instead of "Text"). The updated code would look something like this:

using UnityEngine;
using TMPro;

public class ExampleScript : MonoBehaviour
{
    [SerializeField] 
    private TMP_Text _title;

    public void OnButtonClick()
    {
        _title.text = "Your new text is here";
    }
}

Upvotes: 9

Ivan Taranov
Ivan Taranov

Reputation: 477

Here in Unity, you have a component-oriented design. Text and Button are just Components of GameObject entities. Most parts of your game scripts are also Components that are attached to GameObject. This is a core concept you'd need to realize when you come from JS.

In short, to change a text by clicking the button you need:

1) Create a GameObject with a Text component;
2) Create a GameObject with a Button component;
3) Create a GameObject with a component of your custom script;
4) Create the reference in your custom script on the Text component you want to update;
5) Create a public method in your custom script that will be invoked when you click Button;
6) Assign that method invocation to the OnClick button event through Unity inspector.

Your script will look like this:

    using UnityEngine;
    using UnityEngine.UI;

    public class ExampleScript : MonoBehaviour
    {
        [SerializeField] 
        private Text _title;

        public void OnButtonClick()
        {
            _title.text = "Your new text is here";
        }
    }

Your scene should look like this. Pay attention to the highlighted Title reference. You need just to drag-n-drop Title GameObject here, and that's it.

a

Select your button, assign a GameObject with your script and select a public method that needs to be invoked

a

Welcome in Unity and happy coding!

Upvotes: 14

Related Questions