Update 11/20/15: This tutorial was updated to Unity 5.2 by Pedro Pereira & Orlando Pereira. Original post by tutorial team member Kirill Muzykov.
In previous versions of Unity, the old UI system was downright horrific. It required you to write all your GUI code in OnGUI. It was very programmer-centric which goes against the visual centric nature of Unity itself, and not mention slow and inefficient.Thankfully, the folks over at Unity Technologies have listened.
In this three-part series, you’re going to explore Unity’s new UI system by adding an interactive UI to a small game named Rocket Mouse.
To add a little spice and satisfy your users’ cravings for an engaging UI, you will also:
- Animate the buttons;
- Create a settings dialog that slides into the scene;
- Use more GUI controls like Text, Slider, Panel, Mask and so on;
If you want a sneak peak, just download and run the RocketMouse Final to see what you’ll learn from this tutorial. :]
Getting Started
You will need some images for backgrounds, buttons and other UI elements, as well as a few fonts for the labels and buttons. And no, you won’t have to draw anything yourself or scour the web for the right assets because I’ve prepared a special package that has everything you need. You’re welcome. :]
You can download the package here: RocketMouse_GUI_Assets.
Within the package you will find background images, buttons, icons and other game art, in addition to two fonts from dafont.com. You can thank Rodrigo Fuenzalida for the Titan One font and Draghia Cornel for the DCC Dreamer font.
Lastly, you’ll need to download the starter project containing the RocketMouse game. Download and unpack the Rocket Mouse project using the following link: RocketMouse_Starter.
This is all you need! Well, except love, if you take the Beatles song to heart. :]
Creating MenuScene
Open the RocketMouse_Starter project in Unity by selecting OPEN within Unity’s startup dialog and specifying the root folder of the project.
You’re going to spend most of your time working with a new scene that you’ll create now. From menubar, Select File\New Scene to create a new empty scene.
It’s better to save the scene straight-away, so open the Save Scene dialog by choosing File\Save Scene. Then, enter MenuScene as the scene name and save it to the Scenes folder, right next to the RocketMouse scene.
Take a look at the Project Browser to confirm that there are two scenes in one folder.
Importing Images and Fonts
First on your to do list is to add assets to the scene, so unpack the assets package. There you’ll find two folders: Menu and Fonts.
Select both folders, and then drag them to the Assets folder in Unity’s Project Browser.
Allow a few seconds for Unity to process the files. Then you should see a Fonts folder and a Menu folder in the Project Browser as shown below.
Woo-hoo! You’ve finished the setup and you are ready to create your first UI element using the new Unity GUI system.
Adding your First UI Element
The first element you’ll make is the background image for the menu scene.
From the menubar, select GameObject/UI/Image. This adds an object named Image to the scene. You should see it in the Hierarchy as a child of Canvas. All elements must be placed on a Canvas, so if you don’t already have one, Unity will provide one for you.
To ensure you can see the image in the scene view, select Image in the Hierarchy and set both its Pos X and Pos Y to 0.
You’ll set the correct position and size in a moment – right now, there is another interesting thing to muse upon. Look carefully in the Hierarchy, and you’ll see there are three new objects in the scene:
- Image
- Canvas
- EventSystem
The Image is a non-interactive control that displays a Sprite texture and has many options to tweak.
For instance, you can apply a color to the image, assign a material to it, control how much of the image that displays, or even animate how it appears on the screen using a clockwise wipe.
The Canvas is the root object for all your UI elements and, as previously stated, it’s created automatically when you add your first UI element. It has multiple properties that allow you to control how your UI renders, and you’ll explore some of them during this tutorial.
The EventSystem processes and routes input events to objects within a scene. It is also responsible for managing raycasting. Like the Canvas, it is required for the UI to work so it is also added automatically.
Setting Up the Menu Background Image
The first thing to do is rename your image. In the Hierarchy, select Image and rename to Img_Background.
Next, open the Menu folder in the Project Browser and find the menu_background image. Drag it to the Source Image field of the Image component in Img_Background in the Inspector.
Now you have a background image instead of the default white image. However, it doesn’t look like a good background because it’s too small and the aspect ratio is incorrect.
To fix, find the Set Native Size button in the Inspector and click it to set the size to 1136 x 640.
Now it looks like a proper background.
However, there is still one issue:
- Shrink your Scene view, and you’ll see the Canvas (the white rectangle) covers only part of the image. If you switch to the Game view, you’ll see only a part of the background image, as if the camera is too close to the image to capture it completely.
You’ll tackle this issue by using a Canvas Scaler.
Using the Canvas Scaler
You will use the Canvas Scaler to adjust the way the background image displays.
First, however, you need to know that the display is not the result of a bug. From Unity’s point of view, you have the Game view — or viewport — set to such a small size that it just displays a portion of the image that fits within the Game view.
If you were to run the game on a device with a large enough resolution or simply stretch the Game view to fit the whole image, you would see the entire background image.
Although Unity’s settings make sense in most scenarios, there are times when you need different behavior. An example is when you have a small monitor that doesn’t fit your target device’s resolution.
Additionally, many games support only one resolution. Designers use this reference resolution to dictate sizes, positions, and other data. When you develop a game based on a single reference resolution, you want to make sure to enter the designer’s specifications without additional calculations so that the user sees everything exactly as intended.
If you’ve ever ignored your designer’s directions, surely you know there’s a price to pay. Really though, the user’s experience and the varying resolutions out there are more important, but you have to keep your designer happy, too. :]
Fortunately, a special component comes to the rescue. This component is called Canvas Scaler and you will find it attached to every Canvas.
Select Canvas in the Hierarchy, and in the Inspector, you should see the Canvas Scaler component.
The Canvas Scalar has three modes:
Constant Pixel Size: Makes all the user interface elements retain the same pixel size, regardless of the screen size. This is the default value of the Canvas.
Scale With Screen Size: User interface elements are sized and positioned in accordance to a referenced resolution. If the current resolution is larger than the referenced resolution, then the Canvas will maintain the reference resolution, while scaling up the elements to match the target resolution.
Constant Physical Size: Positions of the user interface elements are specified in physical units such as millimeters or points. This requires the correct reporting of the screen DPI.
Change the component mode to Scale With Screen Size. Set its Reference Resolution to 1136 x 640. Also, slide the Match Width or Height all the way to the right, or simply enter 1 in the input field.
After making those changes, you’ll immediately see the full background image, even in a small Game view window.
Change the Game view resolution to see how your game might look in a different resolution, for example on iPhone Wide 480×320. Nice. It still looks good!
Unity will reprocess all your assets so it may take awhile. At the end, you should now have access to the various iOS screen sizes.
Now switch to the Scene view, and you’ll see the Canvas’s size doesn’t change when you resize the Scene view.
As you can see, the side edges of the screen are neatly cropped, while the central part is fully visible. This is the result of setting Match Width or Height to 1 (match height). It works perfectly for your target resolutions.
And that’s how you manage your designer’s instructions for the background and your users’ many potential resolutions.
But what about the buttons? What happens when they’re very close to the left or the right edge of the screen? You sure don’t want to crop or hide them.
Fortunately, Unity has a feature that will help you sidestep this rookie error. You’ll learn about it soon.
Adding a Header Image
It might have seemed a bit time consuming to add the background image, but that’s mostly because you were setting up the initial UI. Plus, after doing this a couple of times you’ll find the setup to be so fast and easy that you’ll barely have time to blink before you’re done.
Before moving on to buttons and other UI controls, you’ll add one more image — the header image. For this exercise, you’ll use a non-fullscreen image to demonstrate a few other important concepts of Unity’s new UI system.
Open the Scene view and from the menubar, select GameObject\UI\Image. This will add another image somewhere within the scene. Here’s where it ended up for me:
Now, turn that white rectangle into an actual image by following these steps:
- Select Image in the Hierarchy and rename it to Img_Header.
- Open the Menu folder in the Project Browser and search for the header_label image.
- Drag this image to the Source Image field on the Inspector.
- Click Set Native Size in the Inspector.
As you can see, it was easy enough to add another image. Now you just need to work on the positioning, which brings you to your next exercise: working with the Rect Transform component.
Rect Transform, Anchors, Pivot and You
If you worked with Unity before, or at least completed some Unity tutorials on this website, then you’ve probably had some exposure to the Transform component.
If not, that’s fine too. It’s simply a tool that can position, rotate and scale objects in a scene. Here’s what it looks like:
You will see the Transform component when you select any type of non-UI GameObject in your Hierarchy view.
However, if you select any UI element, for example Img_Header, you’ll see a different component named Rect Transform.
As you can see, Transform and Rect Transform look a bit different. Additionally, the Rect Transform can change the way it looks, depending on its Anchor settings. For example, it can look like this:
Here, instead of Pos X, Pos Y, Width and Height, you have Left, Top, Right and Bottom.
Are you wondering about the Anchors setting that changes the look of Rect Transform so dramatically? You’ll find the answers you seek in the next section.
Anchors
Setting Anchors is a simple, elegant and powerful way to control the position and size of your UI elements, relative to their parent. It’s especially handy when you resize the parents.
When you set Anchors, you specify several positions in the parent, usually one in each corner of the parent’s UI element Rect. When the parent is resized, your UI element will try to maintain a uniform distance to the anchor points, thus forcing it to move or resize right along with its parent.
To see different Anchor Presets just select Img_Header in the Hierarchy and click on the rectangle right above the Anchors field in the Rect Transform component.
After clicking, you’ll see various Anchor Presets: these are the most common settings for Anchors. However, you are not restricted to them and you can customize any of them. You can also select different horizontal and vertical behavior for your UI element.
This will all make more sense once you work with it. If you look at the next image, which has the background image disabled, you’ll be able to see the Canvas size changes a bit better.
As you can see, the Anchors settings control how your UI element adapts to screen size changes.
I’m sure you want to try some different settings to understand how they work, but before you do be sure to at least read through the next section. It’ll help you understand Anchors a little better so that you can get more out of your experimentation.
Anchors Manipulator
Currently, the Anchors shown use 4 triangles. Here is how it looks with Anchors set to the top-center preset:
Custom Anchors
You can manually move Anchors to a custom position as the presets are entirely optional — they are just for your convenience.
In this case, just select the anchor icon by choosing an anchor preset (for example, the left-hand side of the screen). The anchor icon will shift to that part of the screen, allowing you to select and move it at will.
Splitting Anchors
You can split Anchors to make them stretch a UI Element horizontally, vertically or in both dimensions.
Look for the word Preview next to the cursor when you try to resize it. Use this technique to experiment and see how your UI elements adapt to different screen sizes.
Rect Transform Depends on the Current Anchors Setting
Depending on the Anchors setting, the Rect Transform provides different ways to control the size and position of your UI element.
If you set Anchors to some single point, without stretching, you’ll see Pos X, Pos Y, Width and Height Properties.
However, if you set Anchors in a way that stretches your UI Element, you’ll get Left and Right instead of Pos X and Width (if you set it to stretch horizontally) and Top and Bottom instead of Pos Y and Height (if you set it to stretch vertically).
In this screenshot, Img_Header’s Anchors are set to middle-stretch. This means that the image stays in the middle of the Canvas vertically and stretches horizontally.
Pivot
There is one final property to discuss in the Rect Transform component, and this is Pivot.
The Pivot is a point around which all transformations are made. In other words, if you change your UI Element position, you also change the pivot point position. If you rotate your UI Element, it’ll rotate around that point.
The Pivot is set in normalized coordinates. This means that it goes from 0 to 1 for both height and width where (0,0) is the bottom left corner and (1,1) is the top right corner.
You can change Pivot in the Rect Transform component in the Inspector or you can use the Rect Tool.
Take a look at the following two images that demonstrate the UI Element with the same Pos X and Pos Y values, yet each shows different placement in the scene.
The first image shows Pivot at its default value of (0.5 , 0.5), which is the center of the UI element. The Position is set to (0, 0) and Anchors are set to top-left.
Now take a look at the second image. As you can see, the position is unchanged at (0,0), but since the Pivot is set to left bottom corner (0,0) you can see that the image’s bottom corner, and not the center, is now placed at the Canvas’s top-left.
It’s harder to show how Pivot affects rotation and size using a still image, so here are few animations:
Observe how the image rotates around the pivot point indicated by a blue circle, which is an element you can freely move.
As you can see, Pivot also affects how your UI Element resizes.
Be aware that there are a few differences between size and scale. For example, size can’t be negative, but scale can be. Also, using a negative scale value will flip your UI element. In most cases, you should only change the size of your UI Elements.
Placing a Header Image
Phew! That was quite a few words dedicated to Rect Transform, Anchors and Pivot. Believe me, you’ll be grateful you spent the time working through the exercise, as understanding them is essential to awesome UI in your games.
Going forward, you’ll concentrate on actually creating the menu scene. The rest of the sections will go by in the twinkle of an eye.
All those manipulations completely exhausted the poor little img_header. It’s time to place it where it should be and leave it alone to recover.
Before you continue, re-enable Img_Background if you disabled it to see the Canvas border.
Then select Img_Header in the Hierarchy and set its properties in the Inspector as follows:
- Click Set Native Size to reset the size, as you probably messed with it while playing around with Pivot.
- Set Anchors to top-center.
- Set Pos X to 0 and Pos Y to -100.
You should see something like this in your Scene view:
That’s it! Now, leave the header image alone. It’s a little tired, too. :]
Adding the Start Button
Now, that your app has a nice background with a label, it’s time to add some buttons.
From the menubar, choose GameObject\UI\Button. This will add a Button object to the scene, you should see it in the Hierarchy. If you expand it in the Hierarchy, you’ll see that the button contains a Text element — you’ll learn about these later.
Look at the button in the Inspector, and you’ll see it has a familiar Image (Script) component, the same as you used to add the background and the header label.
Additionally, there is a Button (Script) component. In other words, a button is just an image with a child Text element and an attached button script.
Positioning the Button
Now it’s all about positioning and resizing the button. Follow these steps:
- Select Button in the Hierarchy view and rename it to Btn_Start.
- Set its Anchors to bottom-stretch, since you want it to stretch horizontally if the screen size changes.
- Set both Left and Right to 350.
- Set Height to 80.
- Set Pos Y to 300.
Then select the nested Text element and set its Text to Start Game. Change the Font Size to 32 to make the text of the button larger.
This is what you should see in the Scene view:
Well…you definitely have a button now, that’s for sure, and it’s in need of a facelift. To make the button look good, you’ll set an image as its background and then use a fancier font.
9-Slice Scaling
You set the image for the Button the same way you set an image for the Image. After all, they use exactly the same component. However, unlike images that rarely scale, especially non-uniformly, buttons often come in completely different sizes.
Of course, you could create a background image for every single button size in your game, but why waste all that space? You’ll use a technique called 9-Slice scaling, which allows you to provide one small image that scales to fit all the sizes.
No, there is no magic involved. You won’t have to put your images in a magic fountain before you can use them :]
This technique works by creating different images for each of nine zones, all of which scale differently.
This ensures the image will look good at any scale.
Preparing Button Images
Before you can use a sliced image, you need to set those 9 zones. To do this, open the Menu folder in the Project Browser and select btn_9slice_normal image.
In the Inspector’s Import Settings, set Format to Truecolor and then click on the Sprite Editor button to open the Sprite Editor view.
In the Sprite Editor, set the Border values to L:14, R:14, B:16, T:16. Remember to click Apply!
Repeat the same process for btn_9slice_highlighted and btn_9slice_pressed images, which you’ll use for different button states.
Setting Button Images
After preparing all images, you only need to drag them to the corresponding fields in the Inspector. Select Btn_Start in the Hierarchy and follow these steps:
- Change Image Type to Sliced in the Image component.
- Change the Transition property in the Button component to SpriteSwap.
- Drag btn_9slice_normal to Source Image in the Image component.
- Drag btn_9slice_highlighted to Highlighted Sprite in the Button component.
- Drag btn_9slice_pressed to Pressed Sprite in the Button component.
Before running the scene and enjoying your cool buttons you are going to take a few seconds to change the font used by the nested Text label. This will make the button mega-awesome.
Setting a Custom Font for the Button
Using a custom font is easy. Remember the Fonts folder in the package you downloaded and added to the project? Now it’s time to break it out and use one of those fonts.
Select the Text element nested within Btn_Start in the Hierarchy. Then open the Fonts folder in the Project Browser and drag the TitanOne-Regular font into the Font field. Also set the Color to white.
Now run the scene and enjoy your new mega-awesome button! :]
Adding the Settings Button
There are only few things left to do before moving on to the next part, and one of them is adding the Settings button.
You can probably do this yourself, so you’re only getting the size and position of the button to start. The rest is almost identical to how you created the Start Game button.
So, here are the properties of the Settings button that are different:
- Name: Btn_Settings
- Rect Transform: Left and Right are 450, Height is 70 and Pos Y is 180
- Text: Settings
This is what you should see in the Scene view after adding the Settings button:
Starting the Game
The final task for this part is to actually click the Start Game button and run the second scene in the game itself.
Adding Scenes to Build
Before you can run different scenes, you need to add them to the Scenes in Build list in the Project Settings, so that they are included in the final application.
To do this, on the menu select File\Build Settings. This will open the Build Settings dialog. Then open the Scenes folder in the Project Browser and drag the MenuScene first, and then the RocketMouse scene to the Scenes in Build list.
Finally, close the Build Settings dialog.
Creating UIManager
When you add an event handler to the button, you need to specify which method to call when you tap the button. Since you cannot use static methods, you will need to select a public method from a script that is attached to a GameObject.
From the menubar, choose GameObject\Create Empty. Then select GameObject in the Hierarchy view and rename it to UIManager.
After that, click Add Component in the Inspector and select New Script. Name it UIManagerScript. Make sure the Language is set to CSharp and click Create and Add.
This is what you should see in the Hierarchy view and the Inspector view:
Double-click on the UIManagerScript in the Inspector to open the script in MonoDevelop. Once the script loads, remove the Start
and Update
methods, and add the StartGame
method as follows:
public void StartGame() { Application.LoadLevel("RocketMouse"); } |
Save the file and make sure it contains no errors by building it within MonoDevelop. Selecting Build\Build All in MonoDevelop’s menu will accomplish this.
Calling the StartGame method when the Player Clicks the Button
Switch back to Unity and follow these steps:
- Select Btn_Start in the Hierarchy and scroll down in the Inspector to the On Click() list.
- Click the + button to add new item.
- Then drag UIManager from the Hierarchy to the newly added item in the list.
- Click on the dropdown to select the function. Right now, it’s set to No Function.
- In the opened menu select UIManagerScript\StartGame ().
Run the scene and click the Start Game button, this should open the game scene.
Where to go From Here?
Stuck on any issues? Feel free to download the completed project for this part.
It might feel like you didn’t do much in this last section but this is not true. You set up the UI, added images and buttons, and even wrote the code that starts the game when you click on the button!
In many games, that’s all that comprises the UI.
You also learned a lot about Rect Transform, Anchors, Pivot and so on. What’s cool is now that you understand them, you’ll be able to move much faster when you apply these new skills to your own projects. You can download the completed project here.
In the next part of this series, you’ll learn how to animate UI elements, create dialogs, and use controls like Slider and Toggle. By the end of it you’ll have a working menu scene.
If you have any questions or comments please leave them below! See you in Part 2!
The post Introduction to Unity UI – Part 1 appeared first on Ray Wenderlich.