0

I am trying to create a list of Toggles added dynamically from a list which works up until I try to add a listener to the toggles. The value passed to SelectColor should increment by one for each toggle but the value passed is exactly the length of the array. putting the index always 1 above the last index for every toggle.

foreach (HexLand color in colors) {
    Toggle option = Instantiate<Toggle> (ColorTogglePrefab);
    option.transform.SetParent (EditorOptions.transform);
    option.name = "Toggle " + color.Name;
    option.group = toggleGroup;
    if (i == 0) {
        option.isOn = true;
    } else {
        option.isOn = false;
    }
    option.GetComponent<HexLandOption> ().label.text = color.Name;
    option.onValueChanged.AddListener (delegate {
        SelectColor (i); // current usage has array length 2. i always returns 2.
    });
    i++;
  }
public void SelectColor(int index) {
    Debug.Log(index); // Writes 2 to console.
    activeColor = colors [index].Color;
}

Is there a method I can use to ensure each toggle returns its value properly?

Meer
  • 2,765
  • 2
  • 19
  • 28

1 Answers1

0

You are capturing i from an outer scope here. The delegate would not execute immediately, so on the moment a callback happens, i already has the last value, which is the length of your array.

Create another variable inside the loop to store the value for an iteration.

See How to tell a lambda function to capture a copy instead of a reference in C#?

Community
  • 1
  • 1
Nerlog
  • 261
  • 1
  • 5
  • I'm not sure how I would properly convert that into a form that fits what I need it to?. I'm not very experienced when it comes to delegates and how they are supposed to work – Raistlin Thoreson Feb 23 '17 at 10:31
  • add a variable before the delegate and use it instead of `i`: `var index = i; option.onValueChanged.AddListener (delegate { SelectColor (index); });` – Nerlog Feb 23 '17 at 10:41
  • the value now does not fall out of range however now it only returns the last value available in the array. – Raistlin Thoreson Feb 23 '17 at 11:31