In this tutorial we will explore the Auto Layout system's Grid Layout, but first let's get to know the Auto Layout system a bit better.
Let's look at how this is set up. On the main camera, a second canvas is added to control the inventory. The parent game object InventoryItems has the Gridlayout Group attached, and is considered a Layout Controller. The Grid Layout controller has several properties to set, depending on how you want your grid to behave.
First is Padding. This is the space on the left, right, top, or bottom **inside** the edges of the layout group. It is the same principle as Padding in the Box Model for web development. For more information on the Box Model, visit the documentation linked in the description below.
Cell Size is the size set for each element in the gird. Just like Excel, the X is the column width, and the Y is the row height.
Think of Spacing as the margin between each column, X, and row, Y.
The Start Corner is the corner where the first element is placed. It works with the Start Axis and Constraint to control how the grid will grow.
If Upper Left, Horizontal is set, as in the Prehistoric Scroller, the next element will be placed to the right of the first cell along the horizontal axis until there are four elements in the row. The fifth element will start a new row.
Child Alignment aligns elements if they don't fill out the available cell space. This is similar to Paragraph alignment options. It is important to remember the children Layout Elements have no control over their sizes.
In the Prehistoric Scroller a script enables the inventory items as the player collects them. Let's add a Sixths item.
Each of the inventory items are actually buttons I know I have a bone item to put into the game so lets make this the inventory bone button. I'll speed things up as I configure the button just like normal. Great! Now let's put the prefab bone item into the scene and see what happens. The bone inventory button displays perfectly in the InventoryItems grid!! Awesome!!
But what if you have an item that is smaller than the cell size you set on the Grid Layout controller?
Let's look at an example. This cracked egg sprite is much smaller than the bone sprite. When I add it as a Layout Element its size is being controlled by the GridLayout controller and its scaled to be larger and doesn't really look nice.
To avoid this,I'm going to remove the button and add a blank UI Image instead. I'll add the Cracked Egg Button as a child of the Image. I'll speed things up as I format the button. Finished! Now next to the other inventory items the cracked egg looks great!