Hi,
I’m trying to add a listener function to buttons on runtime.
On ‘Awake()’ or ‘Start()’ I have tried the following:
m_buttons is a list of buttons. (assume size of 4)
for(int i=0;i<m_buttons.Count;++i)
{
m_buttons[i].onClick.AddListener(delegate{this.OnSelect(m_buttons[i]);});
}
the issue here is that I get index out of range error when clicking the buttons.
However, the following (should be functionally the same) works without problems:
m_buttons[0].onClick.AddListener(delegate{this.OnSelect(m_buttons[0]);});
m_buttons[1].onClick.AddListener(delegate{this.OnSelect(m_buttons[1]);});
m_buttons[2].onClick.AddListener(delegate{this.OnSelect(m_buttons[2]);});
m_buttons[3].onClick.AddListener(delegate{this.OnSelect(m_buttons[3]);});
Another issue I have is the following:
(Assume each button has a different name: ex. button1,button2, button3, button4)
OnSelect(Button sender)
{
Debug.Log(sender.name);
}
Doing this:
foreach(Button b in m_buttons)
{
b.onClick.AddListener(()=>OnSelect(b));
}
Makes every button I press log the name of the last button in the list (Button4).
I have used the above in a different project with no problems, not sure why this is happening. If anyone has any insights on what the cause may be please let me know, thanks!
**I tested the above in blank project just to be sure nothing else is interfering, but I am still getting the same problems. Is this a bug??
**using Unity 4.6.0 f3 (OS X)