Question: Trying out the new uGUI in Unity 4.6, scripting the buttons... Iterate through a directory and create a button for each file... The value of f.Name in the AddListener bit should be set independently for each button. Instead every button has the value of the last f.Name to be processed (the last file alphabetically in the directory). Any ideas?

```
foreach (FileInfo f in fileInfo) {
    Button btnCurrLvl = (Button) Instantiate(btnLvl);

    btnCurrLvl.GetComponentInChildren<Text>().text = f.Name.Remove(f.Name.Length-5);

    Debug.Log(f.Name); // f.Name is different every time
    btnCurrLvl.name = f.Name; // renaming the btns works
    btnCurrLvl.GetComponent<Button>().onClick.AddListener(() => LoadLocalLvl(f.Name)); // all the listeners on all created buttons are set to the last value of f.Name!?
}

```

Answer: 
Be carefull when using lambda expressions inside a foreach loop. The following code:

```
var someList = new List<int> {1, 2, 3, 4};
var listOfClosures = new List<Func<int>>();
foreach (int v in someList)
{
    listOfClosures.Add( () => v );
}

```

is (more or less) equivalent to:

```
var someList = new List<int> {1, 2, 3, 4};
var listOfClosures = new List<Func<int>>();
int v;
for (int i = 0; i < someList.Count; i++)
{
    v = someList[i];
    listOfClosures.Add( () => v );
}

```

Notice that v is declared out of scope of the for loop, and then only reassigned on each pass. Also notice, that the closure keeps only a reference to the variable v. As a result, every single closure in listOfClosures will return 4 when called (the last value v was assigned).

The same happens in your case:

```
foreach (FileInfo f in fileInfo) {
    btnCurrLvl.GetComponent<Button>().onClick.AddListener(() => LoadLocalLvl(f.Name));
}

```

all the closures will hold reference to the same f.
Try creating new variable on each loop pass instead:

```
foreach (FileInfo f in fileInfo) {
    var name = f.Name;
    btnCurrLvl.GetComponent<Button>().onClick.AddListener(() => LoadLocalLvl(name));
}

```
```
string captured;
foreach (FileInfo f in fileInfo) {
  Button btnCurrLvl = (Button) Instantiate(btnLvl);
  btnCurrLvl.GetComponentInChildren<Text>().text = f.Name.Remove(f.Name.Length-5);
  btnCurrLvl.name = f.Name;
  captured = f.Name;
  btnCurrLvl.GetComponent<Button>().onClick.AddListener(() => LoadLocalLvl(captured));
}

```

:)