Button Listener Takes Reference But I Want to Pass Value?

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?

I believe all you need to do here is create a temporary integer within the for loop to store the integer, and pass that temporary integer into the listener.

integers are passed by value by nature, just as any basic data type and struct, so I am suprised that it doesn’t work with just passing i into the listener, but all you should have to do is something like this

for(int i=0; i<buttons.Count; i++)
{
    int tempInt = i;
    buttons*.onClick.AddListener(() => TellFunc(tempInt ));*

}
and it should work the way you want, having each button return individual numbers instead of all of them returning 5 with a list of 5 buttons as an example