What I am trying to do is to get a button to change its own text that is inside of its child. I’ve been trying to first get the GameObject text (the child of the button) and then get component but I keep getting consoles errors.
Here’s the script I used:
void Start()
{
#region Setting variables
public GameObject ObjectButtonText;
public TMP_Text ButtonText;
#endregion
#region Starting setup
ObjectButtonText = gameObject.transform.GetChild(0).gameObject;
ButtonText = ObjectButtonText.GetComponent<TextMeshPro>();
Deselect();
#endregion
}
public void Deselect() //Deselect actions
{
ButtonText.text = "No action selected.";
}
You are defining fields within the Start method, which is odd.
Move those (the things within your “Setting Variables” region) outside the Start method. Then assign the the TMP_Text object within your button to the ButtonText variable in the inspector.
Doing this will make ButtonText have a reference to the TMP_Text, meaning you can then simply change its text as you are doing in the Deselect method, without having to do all the weird Child and Component-getting you attempted.
Here’s how it would look:
public class Potato : MonoBehavior
#region Setting variables
public TMP_Text ButtonText;
#endregion
void Start()
{
Deselect();
}
public void Deselect()
{
if (ButtonText == null) Debug.Log("No button has been referenced!");
ButtonText.text = "No action selected.";
}
}
I managed to solve it. Basically all I had to do was to get the objects which contain the component text and then get the TextMeshProUGUI component from them.