In this section we look deeper into Unity’s UI system, including the various configurations for the Canvas, creating and navigating our own Buttons.
When you create your first UI element, Unity will automatically create a Canvas object inside of your scene, along with the “EventSystem” object that you can ignore for now.
The Canvas is the two-dimensional object that holds your user interface objects. Text, buttons, images, sliders, dropdowns… all of these UI type objects need to be contained inside of a Canvas object. All objects on the canvas are placed using the Rect Transform, a method of rectangular transformation for 2D objects. A Rect Transform defines a rectangle of pixel dimensions W (width) and H (height), and the offsets X and Y measuring the distance the pivot of the object should be placed from the “anchor”. The anchor is a method of defining how it should be offset from it’s parent object, and can be placed at a normalized value horizontally or vertically. The Anchor presets give you options for placement from the Top, Middle, or Bottom vertically, or Left, Center, or Right horizontally. These presets work similarly to text alignment in a word document or spreadsheet cell.
There are two settings inside the Canvas object which are particularly important for setting up your UI. The first is the Render Mode inside the Canvas component. There are three modes available:
- “Screen Space – Overlay” is the default setting and will be your most common use case. This setting causes the canvas objects to be drawn over top of your content on the screen. The canvas will cover the entire area of your screen, and resize if your window resizes. This is similar to the concept of “compositing” video by adding graphics overtop of a video feed. The two do not interact visually at all.
- “ScreenSpace – Camera” works similar to the Overlay method, however it sets the screen out at a distance from the camera, and the camera’s perspective will apply, as opposed to the overlay’s planar projection style.
- “World Space” creates a canvas object in the scene, as opposed to an overlay. This object is a rectangle but has a transform (and thus a position and orientation) within the environment itself. This is what is commonly referred to as a “diagetic” interface, in that it exists within the world itself, rather than just from the perspective of the player/observer.
The Unity Manual has more descriptions and examples of these modes.
The Canvas Scaler controls the way in which objects will respond to different window sizes. You may have noticed that often that the size and placement of UI objects in your game window do not match their size and placement when you run the game at full screen. This is because the Canvas Scaler is set by default to Constant Pixel Size. In this mode, objects retain their width and height values, unaffected by the larger screen. I recommend using the second option, Scale With Screen which will scale the size and positioning of UI objects up and down with the game screen size, thus preserving your layout as it appears in your editor.
If you want to group your buttons into a more formal menu, you can use the Panel object. This simply creates a UI Image object, but one that has a background that mimics the button background, only more transparent. By default, the Panel will fill the screen, but by changing the Rect Transform you can resize it and make objects children of this object.
Panels are an easy way to collect buttons and other UI elements into one place, and can be activated and deactivated. This can be useful for making menus that slide up or over, or populating a tabbed menu. Panels are also useful for gathering UI elements into one location, and for providing contrast for the UI elements against the game view itself.
Unity’s default panel uses the rounded rectangle UI Sprite to soften it’s edges. If you would prefer to use a solid color, just set the Source Image setting to “None”.
To create a button, select Create > UI > Button. This will generate a simple grey button with black text on your screen, and place it in your Canvas. (If you have not created a Canvas yet, Unity will generate one for you.)
You can use the Rect Transform to position the object. Clicking the Anchor diagram will call up the Anchor Presets option. Note the modifiers listed at the top for the Shift / Alt keys. Pressing “Shift-Alt” and clicking the center object will move your button to the middle of the screen.
The text of your button is actually a separate text object – to change the text, find the button object in your hierarchy, and expand it to see the child objects (in this case a “Text” object) and edit the value in the Text field.
To assign a function to a button, you must first have an object in your scene that has a script with a public function. In this case, we are accessing the “UIScript” class that has been attached to the “UIManager” object and lives in the scene.
With the button selected, look at the “Button” component and find the On Click ( ) panel a the bottom.
Click the “+” symbol to add a new On Click action. You’ll see an empty Object field.
Drag the object that with the script or component that contains the method you want to trigger with this button into the Object field.
Next, click the dropdown (currently showing “No Function”) and select the script or component, and then the function you want to run. Now the button press will call that function when clicked. Button Actions can also have up to one parameter.
We can use the same On Click ( ) panel to emit a sound when a button is pressed. We created an empty object and added an audio clip to it, which generated an AudioSource component.
In the OnClick( ) section of our button we add another action, this time adding our sound object, then setting the function dropdown to AudioSource > Play( )
AudioSource is exposed because it is a component of the object, and the Play( ) command is available publicly. Another handy tool is the AudioSource > PlayOneShot( ) method, which lets us play a single pass of an audioClip. Selecting this opens another field of the AudioClip type, and we can drag that directly from our Assets folder into the field, and now it will make that noise when clicked.
Button Sprites (Color & Image)
One way to change the visual appearance of your game is to edit the color of the buttons to move away from the default light gray button that Unity provides. In the Button’s Image component, you can set the Color value to customize the appearance.
The Button component gives you access to the states of the button so that you can provide feedback for selections, presses, and active vs. inactive states. The default Button object uses Color Tint as the method for changing these states, which provides a subtle adjustment to the overall brightness of the button image (but not the text object)
Another way to customize this is to create your own custom button states using sprites. If you ever created your own buttons to build a website, this process will feel familiar – you generate similar images for each and then swap their placement when in the various states. We will look more at this in the next project.
You may have noticed that when we have a button selected, we can use the arrow keys to cycle through the selected option. This is thanks to the Navigation system. By default, Navigation is set to “Automatic”, which means that Unity will try to figure out the logic for itself. Sometimes this logic does not make a great deal of sense, so if you want to see what is going on, click the Visualize button and you will see a flow diagram appear between your UI elements.
The yellow arrows indicate where the selected state will transition when a horizontal or vertical button is pressed. If you want to set these yourself rather than rely on Unity’s automatic setting, open the dropdown and deactivate the items so that only “Explicit” is selected, then you can define the object by dragging it into each directional slot.