- Home /
Adding onClick listener to an array of buttons
I have an array of buttons (ten to be exact) laid out in a scene. Each button corresponds to a level which can be selected by the player. And these buttons are labeled as 1, 2, 3, ..., 10. Simple stuff.
What I'm trying to do is assign the onClick listener to each of these buttons in a simple, iterative fashion as follows:
private Button[] btnArray;
void Start() {
btnArray = GetComponentsInChildren<Button>();
int index = 1;
foreach (Button btn in btnArray) {
btn.onClick.AddListener(() => Application.LoadLevel(index));
index += 1;
}
}
And as you can easily tell, any button click will take the player to the corresponding level. This approach seems to almost work, except when I click on the first button (i.e., level 1), I get an error that pretty much says, "Level 10 cannot be loaded because it has not been added to the build settings."
Well, it's true that I do not have the Level 10 scene in the build settings (I only have Level 1 for now), but I expected it to take me to the Level 1. So, apparently the index value of '10' was passed to the first button instead of '1'. I'd think this would be an easy fix, but it's proven to be rather tricky. :(
foreach loops don't necessarily iterate in indexed order, try using a for loop.
Answer by Mernion · May 30, 2015 at 11:37 AM
This detailed answer could help you: http://answers.unity3d.com/questions/791573/46-ui-how-to-apply-onclick-handler-for-button-gene.html
Your answer
Follow this Question
Related Questions
Move Button OnClick listeners to another button 3 Answers
Canvas button with 2 functions onClick must be pressed twice for 2nd function? Will not disappear? 1 Answer
How to ADD one Buttons.onClick events to another Buttons.onClick? 1 Answer
LoadLevel easy i know, but not working. 1 Answer
Looping through Button Array and checking for OnClick 0 Answers