Question by
tqkiettk10 · Jan 29, 2016 at 02:52 AM ·
uibuttononclicklistener
Add listenner to button in loop error
I have 3 panel contain 20 Button/1 panel.
I try to add onclick listener to first panel but when I click on all buttons it alway print 19. I try to use local index variable but it donot work.
void Start() {
for (int i = 0; i <20 ; i ++)
{
int index = i;
arrayPanelIcon[0].transform.GetChild(index).GetComponent<Button>().onClick.AddListener( () => btnItem_click(index.ToString()));
}
}
public void btnItem_click(string name) {
Debug.Log("click: " + name);
}
Any help, please!
Comment
if I use. It work. Why i cannot use loop? arrayPanelIcon[0].transform.GetChild(0).GetComponent().onClick.AddListener(() => btnItem_click("0")); arrayPanelIcon[0].transform.GetChild(1).GetComponent().onClick.AddListener(() => btnItem_click("1")); arrayPanelIcon[0].transform.GetChild(2).GetComponent
().onClick.AddListener(() => btnItem_click("2"));