Home Game Tech Tutorials

Introduction to Unity UI – Part 2

In this second part of the tutorial, you’re going to add additional functionality like playing and pausing the music, selecting a track from a list inside a ScrollView, and changing the volume with a slider. As you add these features, you’ll learn all about Unity’s built-in UI components.

Version

  • C# 7.3, Unity 2021.3, Unity

Introduction to Unity UI – Part 2

In the first part of this tutorial, you learned all about the Unity Canvas system, how to set up different UIs for different screen resolutions, and the differences between World Space and Screen Space UI. Finally, you set up two buttons to transition back and forth between a 3D scene and a 2D menu.

In this second part of the tutorial, you’re going to add the following functionality to JukeboxHero:

  • Playing and pausing the music.
  • Selecting a category of music from a drop-down.
  • Selecting a track from a list inside a ScrollView.
  • Changing the volume with a slider.
  • Muting the music with a toggle.

As you add these features, you’ll learn all about Unity’s built-in UI components.

Note: This tutorial carries on directly from the end of the first part, so if you haven’t gone through Part 1, go back and read through that now.

Getting Started

This tutorial builds upon what you created in Part 1, so you can use the same project now that you used for the first part. If you need a new copy, download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

Open the starter project in the latest Unity 2021 LTS version. You can use the Unity Hub to download and install the latest version.

Once you’re set up, open the starter project in Unity and open the JukeboxHero scene in the Assets / Scenes folder. Press Play and you’ll see a quaint bar scene with a jukebox playing away to itself in the corner. The World Space UI you made in Part 1 hovers above the jukebox. Clicking the button transitions the camera before fading into a 2D menu with a Back button. Clicking this button reverses the transition.

Showing the result of the part 1

Note: The models for this scene came from Sketchfab. The bar is by gav.grant and the jukebox by Osho. Both were then taken into Blender to convert to fbx format. The UI used in this tutorial is a texture pack from Skolaztika on itch.io.

Speaking of buttons, it’s time to add two more!

Revising the UI Button

Drag two more Button prefabs into the Hierarchy. Drag them from the Assets / Prefabs / Button prefab onto the ScreenCanvas / Panel / Menu GameObject. Name the first one Button Play and the second Button Pause. Change the Text component on each to Play and Pause respectively.

Adding additional buttons

Note: If you can’t see the UI you’re working on, go to the Panel and set the Canvas Group Alpha value to 1. Set it back to 0 any time you want to test the project.

All three buttons will be on top of each other at this stage — which isn’t very useful if you want to be able to click all of them! These buttons should sit neatly at the bottom of the panel, and Unity has another component that will help achieve this.

Create a new Empty Child of the Menu GameObject by right-clicking on Menu and selecting Create Empty. Name this new object Button Layout. This layout should fit across the bottom of the panel, so click the Anchor Presets and while holding Shift select the Bottom Stretch option.

showing the anchor preset settings

This will set the Anchor values to Min (X:0, Y:0) and Max (X:1, Y:0), and the Pivot to be (X:0.5, Y:0) (bottom center). You don’t want it right on the bottom of the panel, so change the RectTransform values to Left & Right: 84, Pos Y: 202 and Height: 125.

Next, add a Horizontal Layout Group component to Button Layout. Change the Spacing value to 6 and the Child Alignment to Lower Center. Uncheck the two Force Expand checkboxes, and check the Control Child Size Width box instead.

showing the recttransform settings

You won’t see anything different in the scene yet. That’s because the Horizontal Layout Group only affects objects that are a child of itself. Drag each of the buttons onto the Button Layout GameObject so they become children of it. Make sure that the Button Back is the first button in the Hierarchy.

Observe what happens to your buttons. Not only have they moved, but they now sit nicely all in a row, and they all fit within the confines of the Button Layout RectTransform.

Showing the layout of the three buttons

Now to make the new buttons do something. Add an event to the OnClick of each. Locate the JukeBox GameObject under Managers in the Hierarchy and drag it into each of the OnClick event’s GameObject slots. For the Button Play, select PlaybackController.Play, and for Button Pause, PlaybackController.Pause.

setting up the playback button

You may have noticed the buttons do look a little squashed now. Also, do you really need a Play button when the music is already playing, or a Pause button when the music is paused?

Select the Managers / JukeBox GameObject in the Hierarchy. Notice in the Inspector the PlaybackController component has open events for OnEnterPlay and OnExitPlay. You can use your events to show and hide the appropriate buttons.

Set the On Enter Play event to turn off the Button Play and turn on the Button Pause, and set the On Exit Play to do the opposite.

Adding the playback events

If you changed the Alpha on the Canvas Group, change it back to 0 then Save the scene and press Play to test your latest changes. When the menu opens, press the Pause button and the audio will stop. When this happens, the Pause button turns off and the Play button turns on. But because of the layout group, it looks like only the text of the button changes!

Showing the results so far

That’s two features knocked out with just three buttons and a layout group! Time to tackle the rest and take a look at some more of Unity’s UI components.

Designing Drop-downs

Drop-downs are a very common piece of UI — particularly in options menus. There’s another prefab prepared for you, so drag it out from the Assets / Prefabs folder onto the same Menu GameObject in the Hierarchy as before.

adding the dropdown prefab

At first, the drop-down doesn’t look especially different than the button. Expand the children of the Dropdown GameObject and you’ll see it has a child named Template that’s disabled. Enable it in the Hierarchy and you’ll see what happens when the user clicks the drop-down in the game.

showing the dropdown prefab components

You can use the template component to customize the look and behavior of the drop-down, but because the actual values for the drop-down can be given from code, you only customize one generic Item for the list. Play around with the design and layout of each of the objects inside the template. You can always revert the changes back to the prefab defaults if you mess it up. When you’re done, turn the Template GameObject off again and go back up to the Dropdown once more.

Take a look at the options inside the Dropdown component:

explaining the dropdown options

  1. Template: This is the GameObject group you just inspected. This group turns on when the player clicks the drop-down.
  2. Caption Text: The Text component that sits on the drop-down itself. It will show the currently selected option.
  3. Item Text: The Text component that sits inside the Item template. This text component will take on the values you put in Options.
  4. Value: The index of the currently selected Option.
  5. Options: Here you input the values that will show up inside the drop-down list.
  6. On Value Changed: This is the event that gets fired when the user selects an option from the list, and the index of that option is sent with the event.

You’re going to use the drop-down to select different categories of music for the jukebox. Select the Managers / Jukebox in the Hierarchy and have a look at the Jukebox component. You’ll see a list of playlists available in the jukebox: blues, classical, old time and swing. Add these as the options to your drop-down. Make sure you type them in the correct order because the selection is index-based. Also notice that the text on the dropdown takes on the value in the first option.

explaining how the dropdown works with the playlists

Your drop-down is set up to filter between the different playlists from the jukebox, but in order to change the track you’ll first need to display a track list for each playlist. For this, you’re going to need a ScrollView.

Adding a ScrollView

You’ve actually already added a ScrollView to the scene! The Template component of the drop-down had a ScrollView on it for when the list of options gets too big for the size of the template. ScrollViews are the perfect solution for when you need to display a large amount of data within a confined space. Whether it’s a list of items, pages of information, or perhaps a large map in a small window, ScrollView can help.

The ScrollView you’re going to need will load a list of tracks based on the selection from the drop-down you just added, so for ease, there’s another prefab ready for you to use. Drag the Scroll View prefab from Assets / Prefabs out onto the Menu object. Like the drop-down, it should be already positioned and ready to use.

Let’s take a look at the anatomy of the Scroll View.

explaining a scrollview

  1. Content: This RectTransform is the most important part of setting up a ScrollView. This is where you layout everything that you want to be able to scroll around and view. The size of the Content RectTransform needs to expand to fit everything, and only when the Content is larger than the Viewport does scrolling have any real effect.
  2. Horizontal and Vertical: These checkboxes turn on and off the scrolling in their respective directions. For a list like the one you’re about to put in, Vertical is sufficient.
  3. Viewport: This is the RectTransform that acts as a window to the content. It should have a Mask component on it so that any content outside of the Viewport is hidden.
  4. Scrollbar settings: This section details the Horizontal and Vertical scrollbars and their behaviors. The scrollbars can be set to Auto Hide so that they don’t display if they aren’t needed.
  5. On Value Changed: Like the drop-down, the ScrollView also raises an event when its value changes. Only the ScrollView raises a Vector2 that tells you the X and Y position it has scrolled to.
  6. Track List: This is an extra script for the Jukebox scene. It will handle loading the appropriate tracks into the ScrollView.
  7. Track Prefab: This is a reference to another prefab — the one for a track listing.
  8. Track List Parent: A reference to the Content RectTransform in the ScrollView. This is where new tracks will be added into the scene.

For the most part, ScrollViews don’t need much setup in order to work. The key thing is to add your content to the Content object and resize it to your needs. For the jukebox, though, the content is going to change depending on the genre selected from the drop-down. That’s where the TrackList script comes in. It’s going to dynamically load new UI objects into the scene at runtime.

For this to work, the Content RectTransform needs to resize depending on what’s loaded in from the TrackList. Select the Content GameObject in the Hierarchy and you’ll see a somewhat familiar component — the Vertical Layout Group — and another component, Content Size Fitter.

explaining a content size fitter

Vertical Layout Group is just like the Horizontal Layout Group you added to the Button Layout earlier in the tutorial, but it lays its children out… vertically!

Content Size Fitter is a component that will drive the size of the RectTransform it’s attached to, based on the layout of its children. It only works in combination with a layout component, such as the Vertical Layout Group. Here, the Content Size Fitter is set to have a Vertical Fit of Preferred Size. This means that as you add more child objects to it, its height will increase so they all fit. Notice that the Height value of the RectTransform is grayed out?

Go ahead and add a couple of child objects to the Content by right-clicking on it and selecting Create Empty. Then, select the Content GameObject again and see that it has a new Height value!

explaining how a ScrollView will automatically expand to fit the content

OK, now that you know how the track listing is going to work, it’s time to hook everything up! Delete any extra GameObjects you added to the Content of the ScrollView.

Select the Managers / JukeBox GameObject in the Hierarchy again, and you’ll see it has two missing references on the Juke Box component. Drag the Dropdown onto the Playlist Dropdown and the Scroll View onto the Track List spaces.

Showing the jukebox playlist setup

The Juke Box script will add a listener to the Dropdown OnValueChanged event that will tell the Track List which playlist to load inside the ScrollView.

If you changed the Alpha on the Canvas Group, change it back to zero and then save the scene and press play. Head into the jukebox menu and start trying out some of the different tracks available.

showing the results so far

Now you’ve finally got a few tracks to listen to, but it’d be great to adjust the volume on the jukebox. And once more, Unity has the perfect component ready for you — the Slider!

Using the Slider

Sliders are another very common UI component when you need to adjust some value. Most settings menus are full of sliders. And changing the volume is the perfect example of such a setting!

Yet again, a prefab is provided in the project. Drag the Volume Slider prefab from Assets / Prefabs onto the Menu GameObject in the scene. Again, it should drop into the correct position.

adding the slider prefab

The Slider component should look familiar because it’s another Selectable with all the same transitions that the Button and Dropdown components had. The Slider-specific settings are:

  1. Fill Rect: This is the RectTransform that acts as the filled in part of the slider. The Slider component drives the Anchor Max value of this component so that it stretches across the Fill Area (another subcomponent of the Slider).
  2. Handle Rect: Similar to the Fill Rect, this component is positioned based on the value of the slider. The only difference is that it’s moved rather than stretched across.
  3. Direction: The slider can be set to either direction in both horizontal and vertical axes.
  4. Min/Max Value: By default, a slider is set just to be 0-1 but you can define any Min and Max value that makes sense for your UI.
  5. Whole Numbers: When using a larger max value, you may want to use whole numbers only. With this on, the slider handle will snap to the appropriate position for whole numbers.
  6. Value: The current value of the slider.
  7. On Value Changed: When the slider value is changed, you can use this event to alert other objects.

You don’t need to change any of the settings on the slider for a volume slider. The only thing to do is to set up the On Value Changed event. A listener is already part of the prefab. Just drag the JukeBox onto the object field and select PlaybackControllerSetVolume from the list. Make sure to select the Dynamic float version from the top of the list, as this will send the slider’s value as the parameter to the function.

setting up the volume function

Save the scene and press Play once more. Play around with the slider once you open the 2D menu and see… no, hear… how the volume changes! :]

Finally, you can set the volume to 0 using the slider, but would it not be handy just to have a mute toggle to do it quickly? One last feature for the road, then!

Adding a Toggle

Fortunately, there’s already a Toggle in the scene for you to use. Expand the VolumeSlider GameObject and you’ll see there’s a Toggle underneath it. This was part of the original prefab you added to the scene. The little volume icon was actually a Toggle all along. Select it in the Hierarchy to see the component details.

showing the toggle settings

  1. Is On: The current state of the Toggle.
  2. Transition & Graphic: The mode that the Graphic will transition, defaults to Fade. And a reference to the checkmark image.
  3. Group: If you want to create Radio Buttons, then you need to add a Toggle Group component to an object, and have all the Toggles reference the same group. Only one Toggle can be on in a group.
  4. On Value Changed: The trusty event! This time it reports a boolean status — the Is On value.

Your final task is to add a listener to the OnValueChanged event. This time, drag the jukebox from Scene / jukebox (the actual 3D jukebox GameObject, not the Manager one) onto the object field and select AudioSourcemute. Again, it’s the Dynamic bool option you want.

setting up the toggle functionality

Save the scene one last time and enter Play mode. Get to the menu and try out all the UI and features you’ve added to JukeBox Hero!

showing the final result

Where to Go From Here

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

You’ve learned all about the different UI components that come standard with Unity. Once you get the hang of these, check out the Unity UI Extensions package. It adds a whole host of new and exciting components for you to use in your projects.

Or, why not design your own components?! Through scripting and the use of the Vertex Helper, you can create completely custom UI components.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!

Contributors

Comments

Reviews

More like this