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?