Button.onClick.AddListener; How to Pass parameter or get which button was Clicked in Handler Method.
Please look at the commont.
void Start ()
{
ButtonPre.onClick.AddListener(SwitchButtonHandler);
ButtonNext.onClick.AddListener(SwitchButtonHandler);
}
void SwitchButtonHandler()
{
//Here i want to know which button was Clicked.
//or how to pass a param through addListener
}
Answer by SeveneduS · Jul 12, 2017 at 11:22 PM
Try this :
void Start ()
{
ButtonPre.onClick.AddListener(delegate{SwitchButtonHandler(0);});
ButtonNext.onClick.AddListener(delegate{SwitchButtonHandler(1);});
}
void SwitchButtonHandler(int idx_)
{
//Here i want to know which button was Clicked.
//or how to pass a param through addListener
}
Dang! Always more capabilities of C# to learn. Time to research what delegate is used for!
Thanks a lot I was just wondering what the difference between using delegate and ()=>, I know the second is a lambda expression, but wondering what the difference between using the 2 are.
Using such a method in the "for" loop and giving the "i" parameter to the delegated method at the end of the cycle will give all the delegated methods one number.
for(int i = 0; i < languageButtons.Length; i++)
{
languageButtons[i].onClick.AddListener(delegate { ButtonLanguageSelected(i); });
}
//All the listeners will share ButtonLanguageSelect(5)
Actually found the solution to it by myself.
for(int i = 0; i < languageButtons.Length; i++)
{
int x = i;
languageButtons[i].onClick.AddListener(delegate { ButtonLanguageSelected(x); });
}
//All the listeners will share different values given to the method
Answer by deluxturtle · Apr 25, 2018 at 04:11 PM
You can also do multiple in the brackets like this.
btn.onClick.AddListener(() => { Function(param); OtherFunction(param); });
This This right here, O$$anonymous$$G thank you, I was looking for this for almost a week. Am I limited in how many Functions I can assign to a button press?
Wow that's so cool!
I want to learn more about this, can you explain the empty brackets before the => operator?
() =>
This notation: () => { /* function body code here*/ }
is called lambda expression, which is a function that is defined inline (in place), unlike defining a function inside a class, with a name. Lambda expressions are nameless and are usually used only once. The parenthesis (not brackets ;) ) define the function's arguments. In this case they are empty, meaning the lambda function accepts no arguments. See this.
Answer by alikun · Nov 16, 2019 at 07:45 AM
You can use: gameobject.GetComponent<Button>().onClick.AddListener(() => Method(5));
Or: gameobject.GetComponent<Button>().onClick.AddListener(new UnityAction(() => Method(5));
Some Mehod: private void Method(int i) { Debug.Log(i) }
Answer by ZMarco · Mar 27 at 10:26 PM
In my case the solution was
for (int i=0; i < buildings.Length; i++)
{
var i1 = i;
button.onClick.AddListener(() => SelectBuilding(i1));
}