Knowing which button was clicked.

Hi all. I tried to search for the answer to this, but I keep ending up with old GUI information rather than information about the new GUI here.

Here’s my issue. I have a lot of buttons. And I want them all to call the same single function in my code when pressed. But, I’d like to know in that function which button was clicked and called the function. So I would like to have each button assigned an ID and have it pass in that ID into the function. Then I know which button was pressed and can proceed accordingly.

Is there any way to get information about which button triggered the event? (I could put a script that assigns an ID to each button, and then use GetComponent to get that script if I can get the GameObject that triggered it… though that may not be the cleanest approach).

This may be a dumb question, but I’m quite inexperienced with this system as it stands.
Thanks in advance for your help.

I have the same issue. On the Beta 19 version these lines of code worked fine for me:

var thisButton : GameObject = UnityEngine.EventSystems.EventSystemManager.currentSystem.currentSelectedObject;
var thisButName : String = thisButton.name;

That I had to change for Beta 20 to:

var thisButton : GameObject = UnityEngine.EventSystems.EventSystem.currentSelectedGameObject;

But for the 4.6 release they have made still more changes to how the event system is exposed and now that throws errors. I can’t figure the ‘release’ way to do the same. My question is here: http://forum.unity3d.com/threads/unity-4-6-multiple-buttons-call-a-function.278801/

See which one gets an answer first.

Problem very similar to this: Get the name of button which has been clicked - Unity Engine - Unity Discussions
You could use my suggestion and modify it a bit to send public id instead of full GO

Thanks but I don’t understand your explanation. And it doesn’t address my question about how to rewrite a line that worked fine in B20 so that it works in RC1. I think that when Unity makes changes in something as fundamental as this they should provide a bit more info than a listing of documentation pages without any code example.

Ok, I figured it out. Tested on buttons and sliders.

var thisButton : GameObject = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;

var thisButName : String = thisButton.name;

Makes the On Value Changed or On Click functions aware of the caller UI object.

1 Like