Kanagalingam
Kanagalingam

Reputation: 2184

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

Upvotes: 0

Views: 13193

Answers (3)

Habibur Rahman Ovie
Habibur Rahman Ovie

Reputation: 281

Just do this after a click event Button.GetComponentInChildren(Text).text = "Button Clicked";

Upvotes: 0

Everts
Everts

Reputation: 10701

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.

EDIT: User wants to change button color on click:

public class Buttontextchange : MonoBehaviour 
{
    public void clicked(Gameobject buttonObj)
    {
        Debug.Log("Button Buy Clicked!");
        Text text = buttonObj.GetComponentInChildren<Text>(true);
        if(text != null){
            textRef.text = "i am a button!";´
        }
        Image image = buttonObj.GetComponent<Image>();
        if(image != null){
            image.color = newColor; 
        }
    }
}

Upvotes: 2

Riaan Walters
Riaan Walters

Reputation: 2676

You are missing the public c# keyword on the Text property. I have changed your script slightly so you can assign the Text and Button references from the Unity Editor

public class Buttontextchange : MonoBehaviour
{

    public Button BuyButton;
    public Text BuyText;

    void Start()
    {
        BuyButton.onClick.AddListener(OnButtonClicked);
        if (BuyText == null)
            BuyText = BuyButton.GetComponentInChildren<Text>();
    }

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

}

Upvotes: 0

Related Questions