I’ve got a list of Button objects and I want to give each of them a different return value so that a function will know which button was clicked/what that button corresponds to. To do this I iterate through a List of Buttons and then give each a listener with the index value of the for loop.
The problem (I believe) is that the listener takes the index variable as a reference and passes that to the listener rather than the actual index value. So the result of having a List of 5 Buttons would be that each would return the value of i (which would be 5 at the end of the for loop) rather than returning 0, 1, 2, 3, 4, 5. The below code shows what I’m trying to do.
public List<Button> buttons;
void Start()
{
for(int i=0; i<buttons.Count; i++)
{
buttons*.onClick.AddListener(() => TellFunc(i));*
- }*
}
void TellFunc(int index)
{
- Debug.Log(“this is button #” + index);*
}
TLDR; Is there any way to make it so that the Button.onClick listeners will take the argument as a value rather than a reference?