Lets say we have added the same event handler for multiple objects at runtime (say a click event handler for several buttons) :
GameObject.Find(“Button_1”).GetComponent().onClick.AddListener(Button_Click);
GameObject.Find(“Button_2”).GetComponent().onClick.AddListener(Button_Click);
GameObject.Find(“Button_3”).GetComponent().onClick.AddListener(Button__Click);
How can we find out which gameobject was clicked ??
void Button_Click()
{
Debug.Log(“THE BUTTON X WAS CLICKED”); ???
}
You have to make the calls different.
The most straightforward way to do this will probably be to add an argument to your function, and then make your buttons call lambda functions that send different arguments to the main function.
void Button_Click(Button clickedButton)
{
Debug.Log(clickedButton.name);
}
Button button1 = GameObject.Find("Button_1").GetComponent<Button>();
button1.onClick.AddListener(() => Button_Click(button1);
Button button2 = GameObject.Find("Button_2").GetComponent<Button>();
button2.onClick.AddListener(() => Button_Click(button2);
Button button3 = GameObject.Find("Button_3").GetComponent<Button>();
button3.onClick.AddListener(() => Button_Click(button3);
Note that it’s important to use a separate variable for each button, because the lambda functions will remember the variable, not its value.
1 Like
Thanks, it worked fine, however it didn’t worked when using an array of buttons such as:
Button[ ] Buttons = new Button[3];
Seems likely that because Buttons[0] = new Buttton(); can’t be accessd due to its protective level.
Post the code that didn’t work, and also an explanation of what it did do when you tried it.
I found the problem : it causes error when using for loop to add listeners:
Buttons[Catalogue] = GameObject.Find(“Button_1”).GetComponent();
Buttons[Catalogue] = GameObject.Find(“Button_1”).GetComponent();
Buttons[Catalogue] = GameObject.Find(“Button_1”).GetComponent();
for (int Index = 0; Index < 3; Index++)
{
Buttons[Index].onClick.AddListener(() => Button_Buy_Click(Buttons[Index]));
}
break;
Sorry , Just posted above by mistake, please ignore it:
I found the problem : it causes error when using for loop to add listeners:
Buttons[0] = GameObject.Find(“Button_1”).GetComponent();
Buttons[1] = GameObject.Find(“Button_2”).GetComponent();
Buttons[2] = GameObject.Find(“Button_3”).GetComponent();
for (int Index = 0; Index < 3; Index++)
{
Buttons[Index].onClick.AddListener(() => Button_Buy_Click(Buttons[Index]));
}
break;
Please use code tags.
Your problem is that you are using the same variable “Index” for all your lambda functions, and they capture the variable instead of its value. When you change the value of the variable “Index” after assigning a listener, the listener changes.
Create a new variable inside your loop so that it’s different for each iteration.
for (int i = 0; i < 3; ++i)
{
Button b = Buttons[i];
b.onClick.AddListener(() => Button_BuyClick(b));
}
1 Like
Thanks for the help, now it worked perfectly.