'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?



Solution 1:[1]

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!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1