- Home /
New UI Button Dynamic onClick Listener problem
Hi everybody, I'm trying to add event listeners to some UI buttons at runtime. I have seen some examples, but for some reason the functions are not being added to my button, even when no error occurs. This is my code:
Script A:
public void DisplayPanel()
{
this.uiPanel = this.levelUIManager.GetLevelPanelFromPool() as LevelUIPanel;
this.uiPanel.SetReplayFunction(() => TestLog());
}
public void TestLog()
{
Debug.Log("Replay");
}
//...
//...
Script B (LevelUIPanel)
public void SetReplayFunction(UnityEngine.Events.UnityAction call)
{
Button button = this.replayButton.GetComponent<Button>();
if(button)
{
Debug.Log("Button Found");//This line prints on console without problem
button.onClick.AddListener(call);
}
}
Thanks in advance for your help
Whoops I accidentally deleted my comment again....
Anyway, shouldn't you call it like this?
this.uiPanel.SetReplayFunction(TestLog);
or this?
this.uiPanel.SetReplayFunction(() => {TestLog();});
Answer by AndresBarrera · Jan 26, 2015 at 12:44 PM
Ok, I found the issue. My button was not calling the functions because there was another invisible button over it swallowing the click events. BUT the Inspector window for my uiPanel button was not displaying the dynamically added events on its list, so I thought there were not being added. This is probably a bug, it is confusing.
Also, for all wondering the syntax to add the functions, it could work with any of the following:
AddListener(() => TestLog());
//Or
AddListener(() => { TestLog(); });
//Or
AddListener(TestLog);
Was having a similar problem but it was because of a UI mask that i had added. That mask was covering my button which is why it was not being detected. I just added the button as a child of the mask and it worked. Hope this helps someone too... :)
Your answer
Follow this Question
Related Questions
Button.OnClic.AddListener(delegate{method(object);}), wrong object sent 1 Answer
button.onClick.AddListener(method); NOT Working 1 Answer
Weird behaviour when trying to dynamically create buttons 0 Answers
Is there a better way to access the single active Toggle in a ToggleGroup? 4 Answers
UI button dosent show function 1 Answer