Unity UI Creation πΌοΈ
User Interface (UI) elements are rendered inside a canvas. A canvas is automatically created when creating a UI element.
Canvas are 2D elements. Click on the 2D button in the scene view to switch to 2D and design the UI more easily.
Positioning Components
Arbitrarily arranging elements in a canvas is not responsive, e.g., the elements will not adapt themselves to the size of the screen.
We often use anchors to place elements. Each element is rendered relatively to a border or another element.
Click on a UI element, and check the "Rect Transform". Then click on this (Anchor presets) . By pressing ALT and selecting an element of the grid, it will automatically position your component somewhere in the canvas, and you can stretch it too if you select one of the stretching icons (increase width, height, both).
Here is an example of positioning an image near the top:
Layout managers
Layout managers are components allowing you to arrange elements more easily. We often create an empty game object for the layout, but it's not mandatory.
The children of the layout game object will be arranged in a specific way, according to the selected layout.
Horizontal Layout
Components are on the same line with a gap (0 by default).
Vertical Layout
One component per line with a gap between lines (0 by default).
Grid Layout
A horizontal layout by default. You can make columns and rows by selecting another value for the field "constraint".
UI Events
You can add a listener, e.g., a method that will be called when an event is triggered:
Add A Listener From The Code
GetComponent<Button>().onClick.AddListener(() => {});
GetComponent<Button>().onClick.AddListener(MyMethod);
Add A Listener From The Editor
You need to add an entry inside "On Click" (ex: Button > On Click).
Select "Runtime Only" and drag and drop a component having the script in which you got the method you want to call. Then select the method in "No Function."
Random Notes
Canvas Scaler
Assuming you didn't use anchors, you can use the "Canva Scaler" component to scale the UI according to the size of the screen.
Set mode to "scale with the screen size" and define the size.
UI Element Background
Any element having the component "Image" can have a background. Drag and drop a sprite in "Source Image".
UI Elements Dimensions
Layouts manage the dimensions of the items, but you can override them. Add a Layout element component and define the custom dimensions/... on the game object.
You can make the text adapt itself to the size of the component using a Content Size Fitter component and setting either or both fields to "Preferred size".
π» To-do π»
Stuff that I found, but never read/used yet.
- UI Builder: new way to build interfaces
- TextMeshPro to write text as a game object
- Button: navigation "automatic"/visualize
- Image: type "Filled", fill amount, slider