Author Topic: multiple uibutton bind event use for loop  (Read 1476 times)

raygenes

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 1
    • View Profile
multiple uibutton bind event use for loop
« on: October 25, 2016, 03:41:48 AM »
  1. Transform items = transform.FindChild ("items");
  2.                 for (int i = 0; i < 6; i++) {
  3.                         UIButton btn = items.GetChild (i).GetComponentInChildren<UIButton> ();
  4.                         EventDelegate.Add (btn.onClick, delegate() {
  5.                                 OnItem (i);
  6.                         });
  7.                 }
  8.  
  9. public void OnItem(int i){
  10.                 Debug.Log (i);
  11.         }
  12.  
  13.  

there is 6 button,name is 1,2,...6,click the button,log always is 7,
How to make log is 1,2,3,4...6?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: multiple uibutton bind event use for loop
« Reply #1 on: October 30, 2016, 11:42:35 AM »
This isn't an NGUI question, but a C# question. However... you need to make a copy of the variable.
  1. for (...)
  2. {
  3.     var copy = i;
  4.     EventDelegate.Add(btn.onClick, delegate() { OnItem(copy); });
  5. }