Dynamic UI with GridLayoutGroup

Let’s say you need to create a UI for a value where you don’t know what the maximum will be. You could just instantiate a new Image/GameObject onto the canvas and then position it manually ooooooor you could let the GridLayoutGroup handle it for you!

In the example above I have clamped the maximum to 3 so the number shields can’t go over the maximum number of lives, but the GridLayoutGroup can be a very powerful tool. Here’s how to set it up.

First, create a “container” object on your Canvas by adding the GridLayoutGroup(GLG) component

This will create a box that will be separated into a grid based off of settings in the component. For ease of understanding, I’ve attached an image to the GLG so that you can see it:

Let’s go through the settings for the GLG one by one so you can get a good understanding of how it works:

Padding: If you’ve done any CSS then you’ll know exactly what this is. It’s the space between bounding box and the element inside of it. I currently have all sides set to 0 so that it will fit perfectly. Nice and snug!

Cell Size: The pixel size of each object within the grid. Generally, it’s good practice to make sure that the dimensions of each cell size divides the corresponding dimensions of the RectTransform perfectly as well. So, the X should divide the Width in the RectTransform perfectly and the Y should divide the Height perfectly. Or “Width % CellSizeX = 0 && Height % CellSizeY = 0” if you remember your mod operator.

Spacing: Creating a space around each grid object before and after the denoted axes. The number of spaces can be determined by “maximum # of objects in a row -1”

Start Corner: Tells the GLG which corner to start counting the grid from. You can choose any 1 of the four

Start Axis: Tells the GLG which direction to create the next object first as long as there is room. Horizontal goes across, Vertical goes up and down

Child Alignment: Tells the GLG where to place the starting object on the GLG

Constraint: Flexible will allow the GLG to automatically format the grid so that all objects stay within the box however, if you only want a maximum number of Columns or Rows then you can set them up here.

If everything is set up properly then all you have to do is just instantiate a new object as a child of the object that has the GLG on it and then the GLG will do the rest! Try it out for yourself! Saves a ton a of time