Ram Jay Ram Jay - 2 months ago 8
C# Question

How to change the text of a button on clicking it in UNITY?

enter image description hereI want to change the text of a Button on clicking it in Unity. I am new to C#. Kindly help me out!

The script which i added to my Button Element

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Buttontextchange : MonoBehaviour {

Text Buy;


// Use this for initialization
void Start () {
Buy = transform.FindChild("Text").GetComponent<Text>();
}

// Update is called once per frame
void Update () {

}

public void clicked()
{
Debug.Log("Button Buy Clicked!");
Buy.text = "i am a button!";

}
}


I have tried a lot of answers but its not working out for me! I have the button inside the canvas. Your help is very much appreciated !
enter image description here

Answer

Your problem comes from the setup of your text and buttons.

The Buttontextchange component is on Buttontext object. I can see on the picture that object has no child. But you run:

void Start () {
    Buy = transform.FindChild("Text").GetComponent<Text>();
}

which is where you are probably getting the error. The Text object is under the Button object so you could just pass it in the onClick call.

public class Buttontextchange : MonoBehaviour 
{
    public void clicked(Text textRef)
    {
        Debug.Log("Button Buy Clicked!");
        textRef.text = "i am a button!";
    }
}

Then in the inspector you drag the text object into the parameter slot.