-1

So, this code is supposed to set onclick events for each button, and each onclick event should have its own id. But, it makes so every button has the same onclick event with the same parameters. The parameter is always 2(there are 2 elements in the array).

 [SerializeField] private Transform buttonsParent;

 private void genButtons()
 {
     for (int i = 0; i < buttonsParent.childCount; i++)
     {
         buttonsParent.GetChild(i).GetComponent<Button>().onClick.RemoveAllListeners();
         buttonsParent.GetChild(i).GetComponent<Button>().onClick.AddListener(delegate { itemPlacer.setId(i); });
     }
 }
derHugo
  • 83,094
  • 9
  • 75
  • 115
CrisDev
  • 11
  • 5
  • Have you tried it without the loop by setting each event handler explicitly? I assume it's related to `itemPlacer.setId(i)`, in each iteration of the loop, you're overwriting the previously set value for `i`. Where is `itemPlacer` defined and what does `setId()` do? Please show more code to understand the problem better. – Julian Dec 25 '22 at 16:38
  • Hey, setId(), does this: public void setId(int value) { if(curItemId == value) { curItemId = 0; } else { curItemId = value; } } And itemPlacer is a separate script. And i cant do it without a loop, because the lenght of the array is always changing or will change. – CrisDev Dec 25 '22 at 16:49
  • Please update the question and those details to it, that's where the information belongs. It's also more legible that way. Also, really include **all relevant information and parts of the code**. – Julian Dec 25 '22 at 17:06
  • 1
    @ewerspej actually that information is irrelevant for the issue ^^ it's a typical closure problem, see duplicates – derHugo Dec 25 '22 at 17:35
  • That's true, but I wanted to make sure that the OP understands that. Anyway, you're right, it's a duplicate anyway. – Julian Dec 25 '22 at 17:41

1 Answers1

0
private void genButtons()
{
    for (int i = 0; i < buttonsParent.childCount; i++)
    {   
        sd(buttonsParent.GetChild(i).GetComponent<Button>(), i);
    }
}
    
private void sd(Button btn, int i)
{
     btn.onClick.RemoveAllListeners();
     btn.onClick.AddListener(() => itemPlacer.setId(i+1));
}
Julian
  • 5,290
  • 1
  • 17
  • 40
CrisDev
  • 11
  • 5
  • I'm glad you solved it. Do you know why this works and the other version didn't? – Julian Dec 25 '22 at 17:24
  • 1
    That is one way .. the more trivial solution would have been a new local variable `var index = i;` and then `buttonsParent.GetChild(i).GetComponent – derHugo Dec 25 '22 at 17:29