- Mastering UI Development with Unity
- Ashley Godbold
- 285字
- 2021-08-27 18:43:16
Automatic Layouts
Now that we have the basics of manually positioning, scaling, and aligning UI elements with the Rect Transform and anchors, we can explore how to use automatic layouts. Automatic layouts allow you to group your UI elements so that they will position automatically in relation to each other.
There are quite a few scenarios in which you will want Unity to automatically control the layout of your UI objects. If you are generating UI items via code and a number of items may change, but you still want them to line up, scale, and position properly, you can use automatic layouts. Also, if you want perfectly spaced UI objects, automatic layouts will help you create this perfect spacing without having to do any position calculating yourself. These automatic layouts work well for things like inventory systems aligned in a grid or list.
In this chapter, we will discuss the following topics:
- Using Layout Group components to automatically space, position, and align a group of UI objects
- Using the Layout Element component, the Content Size Fitter component, and Aspect Ratio Fitter component to resize UI elements
- How to set up a horizontal HUD selection menu
- How to set up a grid inventory
All the examples shown in this section can be found within the Unity project provided in the code bundle. They can be found within the scene labeled Chapter3Text in the Assets/Scene/ExamplesInText/Chapter3Text/ folder.
Each example image has a caption stating the example number within the scene.
In the scene, each example is on its own Canvas and some of the Canvases are deactivated. To view an example on a deactivated Canvas, simply select the checkbox next to the Canvas' name in the Inspector: