multiple rows, in an array in C#

hello there fellow coders!
im completely new to the whole unity and coding in general but i want to learn :slight_smile:
im atm building a little inventory, but i have only mannaged the icons to stack downwards not to the right aswell, i want it so that they show up like 5x4 icons right next to eachother all loaded from my array. here is my code this far.
i hope you know what i can do :slight_smile: thanks alot in advance!

    using UnityEngine;
using System.Collections;

public class inventory : MonoBehaviour {
 public GameObject[] itemSlots = new GameObject[20];
 public int i = 0;

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
 
 void OnGUI () {
 Rect r = new Rect(0,0,35,35); 
    for (i = 0; i < itemSlots.Length; i++){
 if (GUI.Button(r,itemSlots*.GetComponentInChildren().icon)){*

}
r.y += 36;
}

}
}

Just do something like this where you currently add 36 to the r.y:

  r.x += 36;
  if(r.x > 180) {
     r.x = 0;
     r.y += 36;
  }

The following script will do precisely what you want, and a little more. It creates a grid of buttons with the desired top-left grid offset, column width, button size, and button spacing.

 void OnGUI () 
 {
    // square width of each button in pixels
    int buttonSize = 35; 
    
    // number of pixels between the buttons
    int buttonSpacing = 1; 
    
    // top-left position of the button grid
    int xOffset = 20;
    int yOffset = 20;
     
    // number of columns
    int numCols = 5;

    // number of buttons
    int numButtons = 20; // Change this to itemSlots.Length
    
    Rect r = new Rect(0,0,buttonSize, buttonSize); 
    for (int i = 0; i < numButtons; i++)
    {
       r.x = xOffset + (i % numCols) * (buttonSize + buttonSpacing); // column position
       r.y = yOffset + (int)Mathf.Floor((float)i/numCols) * (buttonSize + buttonSpacing); // row position
 
       if (GUI.Button(r, i.ToString())) // change i.ToString() to itemSlots*.GetComponentInChildren().icon*

{
// button was clicked
}
}
}