Hi all,
A bit stuck here. I am getting a clicked button using the EventSystem. It has a Text component as a Child. I can get the name of the button, but not the text in the child. This is my code.
if (ButtonClicked != null)
{
Debug.Log(ButtonClicked);
Debug.Log("The Button Name: " + ButtonClicked.GetComponentInChildren<Button>().name);
Debug.Log("The Button Text: " + ButtonClicked.GetComponentInChildren<Button>().GetComponentInChildren<Text>().text);
}
The last line gives a null reference.
Any help is deeply appreciated.
Are you trying to get the button info via the eventsystem and without placing a function in each buttons onclick on the inspector?
I would personally point to onclick method to a function in a script via the inspector, like so;
using UnityEngine;
using UnityEngine.UI;
public class ButtonInfo : MonoBehaviour
{
public void OnClicked(Button button)
{
Debug.Log("Button Clicked = " + button.name + " : Button Text = " + button.transform.GetComponentInChildren<Text>().text);
}
}
1 Like
Hey, you can get the text component of the button by using the transform component. For example:
public void OnClicked(Button button)
{
Debug.Log("Button Clicked = " + button.name + ": button text = " + button.transform.GetChild(0).GetComponent<Text>().text);
}
Hope this helps
-Joshmond
1 Like
Thanks for the comments. Some things are so obvious when you think about it. Much appreciated.