AddListener Event not returning correct Index

Hi All,

I’m adding buttons dynamically to a custom scrolling panel I’ve written but it does not return the correct button index I press it always return 8 which is the number of buttons in Characters, anybody got a clue why?

Cheers

 private void CreateButtons()
{
  float mButtonHeight = (((RectTransform)this.transform).rect.height * (ButtonHeight * 0.5F));

   if (Characters != null && Characters.Count > 0)
     {
      //int mIndex = 0;
      for (int i = 0; i < Characters.Count; i++)
      {
       GameObject mObject = Instantiate(Prefab, Vector3.zero, Quaternion.identity, this.transform);
       mObject.SetActive(false);

       Characters[i].Button = mObject.GetComponentInChildren<ButtonComponent>();
       Characters[i].Button.RectTransform.sizeDelta = new Vector2(mButtonWidth, mButtonHeight);
       //Characters[i].Button.Title = Characters[i].Title; 

       Button mButton = mObject.GetComponent<Button>();
        if (mButton != null)
          {
           //mButton.onClick.AddListener(() => Button_Click(i));
           mButton.onClick.AddListener(delegate { Button_Click(i); });
           //mIndex++;
          }
      }
     }
}

private void Button_Click(Int32 index)
{
  OnButtonClick(new ButtonClickEventArgs(index)); 
}

you have to save i in a temporary variable.
since i changes on each iteration it will have a different value when the event is actually fired.
so simply do this:

int tmp = i;
mButton.onClick.AddListener(() => Button_Click(tmp));

the variable tmp will stay the same, because there is a separate tmp variable for every iteration in the loop.

3 Likes

Are bummer, I though I tried that, but not the way you mentioned it, as you can see from the commented out mIndex at the start of the for loop, I just tried that and it does not work but YOUR idea does, I purposely did not use the lambda expression because the garbage collector, but cheers none the less.

did you find a fix?