- Home /
Get name of button in c#
Hello, just started with UI 4.6 and try to find out how I can get the name of a selected button object into a script.thanks in advance for help
// Get a reference to the Button component i.e. your button. Assign button from Inspector.
Button button;
// To access and print the game object which contains this button and get the name of that game object
Debug.Log(button.gameObject.name);
// To access and print the name shown in the button.
Debug.Log(button.gameObject.transform.GetChild(0).gameObject.GetComponent<Text>().text);
to all:
solved this some $$anonymous$$utes ago in the way I expected. thank you for your answers.
say you have a cube and there is script attached to it .
void On$$anonymous$$ouseDown()
{
print(transform.gameobject.name);
}
this will print only " cube "
thank you very much. As I wrote above, I solved it already. :-)
Can you recover the missing answers here?
Answer by vfxjex · Dec 26, 2015 at 07:25 AM
say you have a UI Buttonand and on the OnClick Listener you added a gameobject with a script that is executed when button is pressed. this will get the gameobject button name.
string name = EventSystem.current.currentSelectedGameObject.name;
Answer by AlfredoX · Oct 21, 2016 at 09:03 AM
The beautifully concise answer by vfxjex works well for me
string name = EventSystem.current.currentSelectedGameObject.name;
you just need to add this at the top of your code...
using UnityEngine.EventSystems;
Your answer

Follow this Question
Related Questions
Editing buttons created in 'for' loop. 0 Answers
Button Turns Off and On Object 1 Answer
Deactivating a power up script after a certain amount of time 1 Answer
button question 1 Answer
Resolutions 1 Answer