Toggle Dynamically addListener to toggle
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?
the way you pass i into your delegate is referring to i that still gets incremented. to fix that save i in your delegate and use this in between variable as the parameter. that's called a closure.
Furtermore replace delegate with () =>
Your answer
Follow this Question
Related Questions
Make UI yes or no toggle box 1 Answer
How can I add a toggle to this FPS counter script? 1 Answer
How do I save the state of a toggle button? 1 Answer
toggle add listener through script 0 Answers
Issues with fullscreen toggle 0 Answers