When using AddListener, can multiple buttons be registered to the same function?

As the title suggests, is it possible to have n number of buttons register to the same function? I have this so far:

foreach (LevelInfo info in m_LevelList)
{
    info.m_LevelButton.onClick.AddListener( () => 
    {
        Function(info.m_LevelButton);
    } );
}

void MyFunction(Button button)
{
    Debug.Log(button.name);
}

When I use this in application, it only prints the name of the last button in the list.

So, is it possible to register multiple buttons to the same function?

Thanks!

You are closing over the foreach variable with your anonymous method. Each closure will reference the same variable. I’m not going to explain it again, just read the questions at the end which all have the same problem.

The solution is simple. Just create a local variable inside the for loop. This variable will be a new variable each iteration.

foreach (LevelInfo info in m_LevelList)
{
    // local variable which the closure will close over.
    Button button = info.m_LevelButton;
    info.m_LevelButton.onClick.AddListener( () => 
    {
        Function(button);
    } );
}

Some related questions about the same topic:

http://stackoverflow.com/questions/227820/why-is-it-bad-to-use-an-iteration-variable-in-a-lambda-expression