Layout groups
- Game Development course
- Intermediate
- Lesson 35/83
- 4 min
Learn Horizontal, Vertical and Grid Layout Group.
Layout Groups
Rather than manually positioning multiple UI elements (like menu buttons or inventory slots), Layout Group components arrange them automatically.
// Configuring vertical layout group and gap spacing
using UnityEngine.UI;
VerticalLayoutGroup layout = GetComponent<VerticalLayoutGroup>();
layout.spacing = 10f;Whenever an element is added or deleted, neighboring element positions recalculate automatically.
Horizontal, Vertical, and Grid Layout
HorizontalLayoutGroup stacks elements horizontally side by side, VerticalLayoutGroup stacks vertically, and GridLayoutGroup aligns them in a grid. The spacing field dictates gap pixels between items.
// Setting grid slot dimensions to 64x64 pixels
GridLayoutGroup grid = GetComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(64f, 64f);These layout formatters simplify building dynamic inventories and responsive menus.
Practice Print layout type and spacing info
Assign "VerticalLayoutGroup" to layoutType and 10 to spacing. Print Layout: VerticalLayoutGroup | Spacing: 10 to the console.
Starter code
using System;
class Program
{
static void Main()
{
// layoutType ve spacing değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string layoutType = "VerticalLayoutGroup";
int spacing = 10;
Console.WriteLine("Layout: " + layoutType + " | Spacing: " + spacing);
}
}Expected output
Layout: VerticalLayoutGroup | Spacing: 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which component is used to arrange elements like inventory slots in rows and columns in a grid format?
- ParticleSystemRenderer
- HorizontalLayoutGroup
- GridLayoutGroup Correct answer
- AudioMixerGroup
Explanation: GridLayoutGroup arranges child elements into a grid matrix composed of defined rows and columns.
2 Attach vertical layout group
VerticalLayoutGroup vLayout = gameObject.AddComponent<____>();
VerticalLayoutGroup vLayout = gameObject.AddComponent<VerticalLayoutGroup>();
Explanation: A VerticalLayoutGroup component is attached to stack UI elements vertically one below another.
3 Layout formatters
| Term | Meaning |
|---|---|
HorizontalLayoutGroup |
Arranges UI side by side horizontally |
VerticalLayoutGroup |
Arranges UI vertically one under another |
GridLayoutGroup |
Arranges UI in row-column grid |
spacing |
Pixel gap between elements |