- Home /
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
Answer by knudsjef · Aug 02, 2015 at 08:10 AM
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;
Answer by omaglana · Aug 23, 2018 at 08:32 AM
The accepted answer gives me syntax error. It should be:
private Button _button;
Awake(){
_button = GetComponent<Button>();
}
Start(){
_button = GameObject.Find("_buttonName").GetComponent<Button>();
}
Answer by Izacrivera · Sep 06, 2020 at 07:23 PM
A button is a simple Game Object with a button component, so try this:
GameObject.Find("GameObjectName").GetComponent<Button>();
Answer by HyosokaPoipo · Jun 01, 2017 at 01:45 PM
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... :)