New UI : Need help with buttons

I cannot find anything on how to access different components on a button or text, or anything in the canvas via script. I have watched the tutorial videos, and they did not cover what i am trying to do. Any help would be greatly appreciated.


Unity UI has been thought hierarchically. A component may often be a sub-component.
For example, a Text is a sub-component of a Button.

If you want to reach the UI transform:

var rectTransform = GetComponent<RectTransform>();

From that one, you can reach:

rectTransform.sizeDelta // is the size of the UI.
rectTransform.anchoredPosition // is the position of the UI.

Else if you want to modify a Button:

var button = GetComponent<Button>();

Or a Text:

var text = GetComponent<Text>();

In the case you want to change the text of a button, the only way I know is actually:

var button = GetComponent<Button>();
var text = button.GetComponent<Text>();
text.text = "New text";

Or this might work as well:

var text = GetComponentInChildren<Text>();
text.text = "New text";

Remember that using those classes required to use this namespace:
using UnityEngine.UI;

UI scripts are in the UnityEngine.UI namespace.

You can find them in the scripting reference. For ex for button: