- Home /
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 :) 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 :) 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[i].GetComponentInChildren().icon)){
}
r.y += 36;
}
}
}
Answer by whydoidoit · Jul 08, 2012 at 10:31 AM
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;
}
ah that worked! thanks man! :D took a little to understand what you ment hehe had some mouse trapping and stuff happening xD
Probably needs to be >= 180 on reflection.
Or you could move the rect definition into your loop and do:
var r = new Rect((i%5)*36,(i/5) * 36, 35,35);
Answer by Brian Stone · Jul 08, 2012 at 10:58 AM
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[i].GetComponentInChildren().icon
{
// button was clicked
}
}
}