Making a grid of buttons is hard!

In my personal pursuit of an inventory system for my game, I decided to try doing it from scratch as a learning experiment.

From what I’ve seen on the forums and read in the docs, using a selection grid would not be the way to go, because they’re relatively resource intensive and it doesn’t really suit my needs (only one active button, etc.)

All I’ve done so far is set up the basic grid of GUI buttons, and that alone was pretty confusing!

Here’s what I came up with… is this the easiest way to do achieve what I’m going for?

var inventory : Array;
var inventorySize = 16;
var iconWidthHeight = 50;
var iconOffset = 10;
var iconsPerRow = 4;

function Awake () {
	inventory = new Array(inventorySize);
}

function OnGUI(){

	var rowCounter : int = 0;
	var rowWidth : int = (iconsPerRow*iconWidthHeight)+(iconsPerRow*iconOffset);

	for( var i = 0; i < inventory.length; i++ ){
		if( ( i%iconsPerRow ) == 0  i > (iconsPerRow-1) ){
			rowCounter++;
		}
		GUI.Button (Rect ( ((i*iconWidthHeight)+(i*iconOffset))-(rowWidth*rowCounter),(rowCounter*iconWidthHeight)+(rowCounter*iconOffset),iconWidthHeight,iconWidthHeight), "");
	 }

}

[/code]

Your code looks pretty good to me! There are a few other approaches you could use of course. One that comes to mind:

Loop through the vertical rows.
   Loop through the horizontal columns.
      GUI.Button(getRect(vert_offset,horiz_offset), "")

function getRect(vert_offset,horiz_offset)
    return a standard-sized Rect with the correct vertical and horizontal positioning

I’m not sure if that’s any “simpler”, but it does separate out your code more and make it easier to read maintain.

Ohh, I see now! That’s how many of the examples of inventories I’ve seen are set up, but without it being explained in simpler terms I couldn’t fully understand what the loop inside the loop was doing.