- Home /
Rows and columns of buttons in a for loop
Hello everyone,
For my inventory system, i want to have a grid of 3 x 3 buttons, so a total of 9 buttons. I now have a for loop that counts how many items i have in my inventory array (list) and creates a new button for every item in my inventory array. However, i have no clue how to get multiple buttons next to each other with a Begin- and EndHorizontal inside a for loop. And to be honest, i haven't use for loops often.
This is a little bit of the code i have:
 function OnGUI() {
     if (showInventory) {
         GUILayout.BeginArea(Rect(Screen.width/2 - 350/2, Screen.height/2 - 400/2, 350, 400), inventoryStyle);
             GUILayout.Label("Player inventory");
             for (var i=0; i<playerInventory.Count; i++) {
                 GUILayout.BeginHorizontal();
                 GUILayout.Button(playerInventory[i].icon);
                 GUILayout.EndHorizontal();
             }
         GUILayout.EndArea();
     }
 }
I hope it is simple to add more buttons to each row.
Thanks in advance!
Answer by Negagames · Apr 25, 2013 at 01:38 AM
Take GUILayout.BeginHorizontal(); and GUILayout.EndHorizontal(); out of the for loop.
If i do that, every button will be squished in one horizontal line, ins$$anonymous$$d of a 3x3 grid.
I thought i came up with a solution, but it doesn't work. Please, can anyone help me out? This is what i came up with, but doesn't work:
 function OnGUI() {
     if (showInventory) {
         GUILayout.BeginArea(Rect(Screen.width/2 - 350/2, Screen.height/2 - 400/2, 350, 400), inventoryStyle);
             GUILayout.Label("Player inventory");
             for (var i=0; i<playerInventory.Count; i++) {
                 if (i>=0 && i<=3) {
                     GUILayout.BeginHorizontal();
                     GUILayout.Button(playerInventory[i].icon);
                 }
                 if (i>3 && i<=6) {
                     GUILayout.EndHorizontal();
                     GUILayout.BeginHorizontal();
                     GUILayout.Button(playerInventory[i].icon);
                 }
                 if (i>6 && i<=9) {
                     GUILayout.EndHorizontal();
                     GUILayout.BeginHorizontal();
                     GUILayout.Button(playerInventory[i].icon);
                     GUILayout.EndHorizontal();
                 }
             }
         GUILayout.EndArea();
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
For loop not working 1 Answer
crazy loop !!! HELP ME 1 Answer
Easy way to get every wheelcolliders hit data 1 Answer
x=x Assignment made to same variable 3 Answers
How do we implement a for loop 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                