Unity New GUI Tutorial – Part 1

Unity New GUI Tutorial – Part 1

Unity New GUI Tutorial

You will love getting gooey with Unity’s new GUI!

There’s no denying that Unity is an awesome game engine. By catering to the needs of the independent developer while also providing features of premium AAA engines, it’s no surprise that Unity is a now mainstay in game development.

Unfortunately, every Achilles has his heel and for Unity, that was the old GUI system.

The old GUI system was a painful system that 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.

There were third party tools such as NGUI that aimed to solve this problem, but it’s a little frustrating to have to pay more money for something that should be included with the base package.

Well, the folks over at Unity Technologies have listened. After two years of development, they have provided a solution that will erase those past pains. With the release of Unity 4.6, you have access to an entirely new GUI system, and you’re going to learn all about it this tutorial, right here, right now.

In this three-part series, you’re going to add new GUI to the game created in our previous tutorial series – How to Make a Game Like Jetpack Joyride in Unity 2D.

Note: If you haven’t completed the original tutorial, it’s okay, but it wouldn’t hurt to go back through it. If you start there, when you get to the end of this series, you’ll have a fairly functional game, rather than just a project with a simple menu scene. You’ll also see how you can migrate from the old GUI system to the new one, and that’s just priceless.

As you work through this tutorial, you’ll add a classic main menu scene to the game.

Unity 4.6 New GUI

However, simply adding few buttons isn’t sufficient for you to master new GUI system. To add a little spice and satisfy your users’ cravings for engaging UI, you’ll

  • Animate the buttons
  • Create a settings dialog that slides into the scene
  • Use more new GUI controls like Text, Slider, Panel, Mask and so on.

If you want a sneak peak, just download and run the final project to see what you’ll learn from this tutorial. :]

Getting Started

To start, you’ll need some images for backgrounds, buttons and other UI elements, as well as a few fonts for the labels and text on the 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 can download the package here: RocketMouse_GUI_Assets

This package contains background images, buttons, icons and other game art created by my lovely wife Svetlana.

You’ll also find two fonts from dafont.com. For those cool fonts, thank Rodrigo Fuenzalida (Titan One font) and Draghia Cornel (DCC Dreamer font)

As mentioned, you’re going to add a new scene to the Rocket Mouse project created in previous series, so start by downloading the final version of that project: RocketMouse_Final

This is all you need! Well, except love, if you take the Beatles song to heart :]

Creating MenuScene

Download and unpack the Rocket Mouse project using the link above. Open this project in Unity by selecting File\Open Project… within Unity and specifying the root folder of the project.

Note: Alternatively, open the Assets\Scenes folder within the project folder and double-click on RocketMouse.unity scene to open Unity.

After the project loads, you’ll see a comfortably familiar scene that looks as it did when you left off, or, a scene that is completely new to you — depending on whether you completed the original tutorial. In any case, keep calm and read on. :]

You’re going to spend most of your time working with a new scene that you’ll create now. Select File\New Scene in the menu 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 there’s two scenes in one folder.


Note: If you encounter any issues while opening the project, creating or saving the scene or adding assets, then go work through the original Rocket Mouse tutorial. There you’ll find detailed, step-by-step instructions — often in form of animated GIF images that are not included in this tutorial, for the sake of staying true to the DRY principle. :]

Importing Images and Fonts

First on your todo 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 view.

Allow a few seconds for Unity to process the files. Then you should see a Fonts and Menu folder in the project browser as shown below.

Woo-hoo! You’ve finished the prework, and can now create your first UI element inside the new Unity GUI system.

Adding your First UI Element

The first element you’ll make is the background image for the menu scene.

Select GameObejct/UI/Image in the menu. 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 its Pos X and Pos Y to 0.


Note: I can already hear questions like, “What’s Pos X?”, “What’s the Rect Transform component and where is the familiar Transform component?”

As you work through this, you’ll find answers to your burning questions. It’s easier to learn about them in the context of other objects in the scene, so that you can observe behaviors with different settings.

Properties like Width and Height or Pos X shouldn’t require any explanation.

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.

You should see these:

  1. Image
  2. Canvas
  3. 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 or place materials on it. You can even control the amount of the image that displays. Bring it to life with an animation “appear” such as a clockwise wipe.

The Canvas is a 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 is responsible for processing and handling input, raycasting and the events within a Unity scene. It’s required for the UI to work, so that’s why it was added automatically.

Setting up Menu Background Image

It’s time to get back to the Image, and the first thing to do is rename the Image 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 1024 x 577.


Now it looks like a proper background.


However, there are still few issues:

  1. The actual size of the image is 1136 x 640, which is just enough to cover the full screen of a 4-inch iPhone.
  2. Shrink your Scene view, and you’ll see the Canvas (the white rectangle) covers only the 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.


Note: The original game was designed for iPhones with 3.5- and 4-inch displays. This is why all the game art supports 1136 x 640 and 960 x 640 resolutions. But soon you’ll see how the UI can adapt to different game resolutions.

The first issue is the result of the default Import Settings, and you’ll fix them in the next section. You’ll tackle the second issue by using a Reference Resolution Component.

Fixing the Image Import Settings

You need to allow slightly bigger images for your project, and prevent Unity from scaling them down.

Open the Menu folder in the project browser and select the menu_background image. In the Inspector, select Default tab and set Max Size to 2048 and click Apply.


Now select img_background in the hierarchy, and then click Set Native Size again. The width and height should change to correct values of 1136 and 640, respectively.


See? That was indeed an easy fix to make. Onto the next fix!

Using the Reference Resolution Component

When you have the correct background image in the scene, it’s time to adjust the way it displays.

First of all, 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 the small size of 550×310, so it just shows you a portion of the image that fits in the Game view.

If you were to run the game on a device or simply stretch your Game view to fit the whole image, you’ll see the entire background image.

Although Unity’s settings make sense in most scenarios, there are times when you need different behavior. Like 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. So, when you develop the game you want to make sure to enter the designer’s specifications without additional calculations, so 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 Reference Resolution and you need to add it to the Canvas component.

Select Canvas in the hierarchy, and then click on Add Component. Start typing Reference Resolution to find the required component and click on it as soon as it shows in the list.


After adding the component, set its 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 3-5 inch iPhone. Nice. It still looks good!


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 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 a new GUI system.

Open the Scene view and select GameObject\UI\Image in the menu. This will add another white image somewhere to the scene. Here’s where it ended up for me:


Note: Should the image in end up in the hinterlands, just set its Pos X and Pos Y properties to 0

Now, turn that white rectangle into an actual image by following these steps:

  1. Select Image in the hierarchy and rename it to img_header.
  2. Open the Menu folder in the project browser and search for the header_label image.
  3. Drag this image to the Source Image field on the Inspector.
  4. 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 with 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 select any type of GameObject in your Hierarchy.


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, but the Rect Transform can change the way it looks, depending on the Anchor settings. For example, it can look like this:


Note: Instead of Pos X, Pos Y, Width and Height, you work with 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.


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 UI element Rect. When the parent is resized, your UI element will try to maintain 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, but you’re not restriced to them and can customize 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:


Custom Anchors

You can manually move Anchors to a custom position as the presets are entirely optional — they are just for your convenience.

Note: You might find yourself in a situation where the translation gizmo covers the anchor icon, making it impossible to select the anchor.

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.


Note: See how the image moves to the right when you resize the Canvas? However, it moves only a little in relation to the right edge of the Canvas. This happens because Anchors are set to 25% width of the Canvas.

Splitting Anchors

You can split Anchors to make stretch a UI Element horizontally, vertically or in both dimensions.


Note: You’re not actually resizing the Canvas when dragging one if its edges. In fact, you can’t resize the Canvas this way.

Look for the word Preview, next to the cursor when you try to resize it. Use it to experiment with sizes 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 such 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 get 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.


Since Pos X and Width depend on the size of the parent, set the padding from the left and right edges of the parent.


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 set your UI Element position, you set the pivot point. 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.

Note: You can also set Pivot outside the UI Element bounds. In this case, Pivot will be outside (0,0) – (1,1) range. This can be useful. For example, you might want to rotate your object around some point in the scene. To alter you pivot, you must make sure Pivot/Center button is toggled to Pivot like so: Pivot / Center button

You can change Pivot in the Rect Transform component in the Inspector or you can use the Rect Tool.


Take a look at following two images that demonstrate the UI Element with the same Pos X and Pos Y values, but 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.


Note: It’s important to understand that position of the UI Element is set relative to Anchors. This is why (0,0) position means the distance from Anchors, which are set to top-left corner of the Canvas.

Now take a look at the second image. As you can see, 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:


Please note how the image rotates around the pivot point indicated by a blue circle, which is an element you can freely move.


Note: Hold the ALT key while scaling to scale around the pivot point.

As you can see, Pivot also affects how your UI Element resizes.

Note: Another important thing to understand is that when you change the size of UI Element, you don’t change its Scale. Instead, you change its size e.g. Width and Height or Top, Right, Left, Bottom paddings.

There are a few differences between those. For example, size can’t be negative, but scale can be; using negatives 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:

  1. Click Set Native Size to reset the size, as you probably messed with it while playing around with Pivot.
  2. Set Anchors to top-center.
  3. 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.

Choose GameObject\UI\Button in the menu. 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 label — 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 an attached button script that contains a Text.

Note: The text label is optional, so if you have a button image with text drawn right into the image, you can delete the text element. You’ll do this a couple of times during this tutorial.

Positioning the Button

Now it’s all about positioning and resizing the button. Follow these steps:

  1. Select Button in the hierarchy and rename it to btn_start.
  2. Set its Anchors to bottom-stretch, since you want it to stretch horizontally if the screen size changes.
  3. Set both Left and Right to 400.
  4. Set Height to 80.
  5. Set Pos Y to 300.


Then select 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 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 makes this possible because the image does not scale evenly. There are nine zones, each 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.


Note: Setting Format to Truecolor is not required and not related to image scaling. However, I experienced compression artifacts with my set of images, so I found that it’s better to do this. If you use your own images and they look good in the compressed format, then you don’t need to tinker with this setting.

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 corresponding fields in the Inspector. Select btn_start in the hierarchy and follow these steps:

  1. Change Image Type to Sliced in the Image component.
  2. Change the Transition property in the Button component to SpriteSwap.
  3. Drag btn_9slice_normal to Source Image in the Image component.
  4. Drag btn_9slice_highlighted to Highlighted Sprite in the Button component.
  5. Drag btn_9slice_pressed to Pressed Sprite in the Button component.


Note: If you encounter this error message, This image doesn’t have a border, then you probably forgot to set the Border in the Sprite Editor in the Import Settings as described above.

Before running the scene and enjoying your cool buttons you’ll going to take a few seconds to change the font used by the nested Text label. This will make the button mega-awesome.

Setting Custom Font for the Button

Using a custom font is easy. Remember the Fonts folder in the package you downloaded and added it to the project? Now it’s time to break it out and use one of those fonts.

Select the Text label nested in the 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! :]


Removing Button Transparency

Did you notice that you could see the background through the button? Depending on what you’re trying to achieve, this can be good or bad. For the main menu on this game, it’s better to remove this transparency.

Note: I believe this transparency is added by default, because in many cases you have your UI on top of your game view and want the player to see through buttons such as pause or joystick.

It only takes a few seconds to undo this. Select btn_start in the hierarchy and double-click on the Color property inside the Image component. In the opened color picker dialog set A (Alpha) to 255 and close the color picker.


Now it looks much better!


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.

Note: The easiest way is of course to duplicate the button and adjust some properties, but try creating the button from scratch since you’re here to learn.

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
Solution Inside: Need help creating the Settings button? SelectShow

If you couldn’t quite do it, just follow these steps:

  1. Select GameObject\UI\Button in the menu. This will create a Button object in the scene.
  2. Select Button in the hierarchy and rename it to btn_settings
  3. Set the button Anchors to bottom-stretch.
  4. Set both Left and Right in Rect Transform to 450.
  5. Set Height to 70 and Pos Y to 180.
  6. Set Transition in the Button component to SpriteSwap.
  7. Make sure to set Image Type in the Image component to Sliced.
  8. Open the Menu folder in the project browser and drag btn_9slice_normal to Source Image
  9. Then drag btn_9slice_highlighted to Highlighted Sprite.
  10. And finally, drag btn_9slice_pressed to Pressed Sprite.
  11. Double-click on Color inside the Image component and set A to 255 to remove the transparency.
  12. rmouse_ui_53
  13. Select nested Text label.
  14. Change Text to Settings
  15. Set Font Size to 24
  16. Change Color to White.
  17. Open the Fonts folder in the Project Browser and drag TitanOne-Regular font into the Font field in the Inspector.


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 select File\Build Settings… to 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.

Note: The order is important. Follow it!


Then 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. This means you need to attach an object to a script, since you can’t use static methods.

So, add an empty GameObject and attach a script to it. This script will contain all methods called by UI elements in the MenuScene.

Choose GameObject\Create Empty in the menu. Then select GameObject in the hierarchy 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 and the Inspector:


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()

Save the file and make sure it contains no errors by building it within MonoDevelop. Selecting Build\Build All in the MonoDevelop’s menu to do this.

Calling the StartGame method when the Player Clicks the Button

Switch back to Unity and follow these steps:

  1. Select btn_start in the hierarchy and scroll down in the Inspector to the On Click (Button) list.
  2. Click the + button to add new item.
  3. Then drag UIManager from the hierarchy to the newly added item in the list.
  4. Click on the dropdown to select the function. Right now, it’s set to No Function.
  5. 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?

It might feel like you didn’t do much in this last section of this tutorial. 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 that 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, use controls like Slider and Toggle, and 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!

Unity New GUI Tutorial – Part 1 is a post from: Ray Wenderlich

The post Unity New GUI Tutorial – Part 1 appeared first on Ray Wenderlich.



Write a comment