I 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 !
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;
}
}
}