- Home /
Best way to create large amount of buttons
I am needing to create 15 buttons which are in 3 rows of 5. I have tried using a for loop but this does not work due to GUI.Buttons being in an if statement. How do you create buttons in a loop so I do not have to have a large amount of code for the buttons?
Just for all those people out there, if you put an if statement for a button in a for loop it pauses the loop because it is waiting for the true statement to be returned. Simply putting the if statement in the for loop does not work.
Answer by Chronos-L · May 31, 2013 at 08:22 AM
public class Buttons : MonoBehaviour {
void OnGUI(){
for( int i = 0; i < 15; ++i ) {
if( GUILayout.Button( "Click " + (i).ToString() ) ) {
Debug.Log( i );
}
}
}
}
I am pretty sure that this works.
Answer by bodec · May 31, 2013 at 07:30 AM
you need to place the if statement inside the for loop so each time throu the loop it creats a button that can be pressed.
as you loop throu you will need to increment the position other wise it will stack all the buttons in the same place
there is no 2 lines of code that will create 15 buttons if that is what you are asking.
No I am not an idiot, I did increment the position and used Debug.log to check if it was actually going through the loop but it doesn't because the button doesn't return true until it has been clicked.
But that's how you do it :-) . It depends entirely on your code, so it's impossible to tell what you did wrong without seeing your code and a brief description what these buttons should do.
Feel free to edit your question and add more details.
Your answer
Follow this Question
Related Questions
Gui Button Solid 2 Answers
Key for GUI.Button 2 Answers
On Clicked, On Released GUI Button ? 2 Answers
Use a key to open a GUI? 2 Answers
Linking button press with questions 3 Answers