I have an array of Button objects that I want to pass a function with different arguments into. This function takes an int argument. I've tried the following:
public void ButtonClick(int i){
//do things with value of i
}
public void FillButtonClicks(){
for(int i = 0; i < 3; i++){
ButtonArray[i].AddListener(delegate{ButtonClick(i);});
}
}
This "works" in that the buttons receive the appropriate delegates, but it does NOT work in that the garbage collector is holding onto the value of 'i' in the for loop, i.e., when I click any of the three buttons, they all execute ButtonClick(3). Is there a way to enforce the passing of values, or do I have to just do something dumb like:
ButtonArray[0].AddListener(delegate{ButtonClick(0);});
ButtonArray[1].AddListener(delegate{ButtonClick(1);});
ButtonArray[2].AddListener(delegate{ButtonClick(2);});