How to Find a UI button by name in unity 4.6

i have a script which need to access a button. but i cant figure out how can i set a button to a variable. for a gameobject i can use GameObject.Find() but what can i use for a Button

Make sure you are using UnityEngine.UI; You can do this by where it says using UnityEngine; you also put using UnityEngine.UI; then get the button by ButtonObj = GameObject.Find(“Button”).GetComponent;

A button is a simple Game Object with a button component, so try this:


in Unity 5.6, we can use GetComponentsInChildrend();

So for example in my canvas UI, I have 2 buttons, then I want to access those buttons using private Button in my scripts. So we can do something like this :

void Start () {
	cvs = GetComponent<Canvas>();
	restart = GetComponent<Canvas>().GetComponentsInChildren<Button> ();
	Debug.Log (restart[0].tag);
	Debug.Log (restart[1].tag);

My first button in the hierarchy will be in first index array and the second button will be in next array, we can know that by Loggin their tag as shown above…

I hope this can help… :slight_smile:

The accepted answer gives me syntax error. It should be:

private Button _button;

_button = GetComponent<Button>();

_button = GameObject.Find("_buttonName").GetComponent<Button>();