Chapters

Hide chapters

Unity Apprentice

First Edition · Unity 2020.3.x LTS Release · C# · Unity

Before You Begin

Section 0: 4 chapters
Show chapters Hide chapters

7. User Interfaces
Written by Eric Van de Kerckhove

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

In the last chapter, you explored the wonderful world of Unity’s input systems, and you learned the basics of the physics system. Now that you can move the player avatar around in the world, it’s time to add a title screen and make a user interface for the dialogue system. Along the way, you’ll learn all about the most common UI elements and how to create windows that can automatically resize to fit their contents. You can use this to let the NPCs tell the player avatar anything you want — like silly dad jokes, for example!

Whether it’s bouncy hearts that show your remaining lives, a green stamina meter that lets you know how many more dodge rolls you can perform or a simple piece of text that explains the stats of your equipped weapon, user interfaces are everywhere.

A user interface — commonly referred to as the UI — can consist of text, images, sliders, buttons and more. The combination of these elements is crucial to delivering information to the player.

Title screen overview

As a minimum, a title screen should show a game’s name and a way to start playing. More elaborate title screens can include an options screen and a way to show the credits. They might even have dynamic backgrounds. In the case of the Veggie Gladiators game you’ve been tinkering with for the last two chapters, the title screen is simple, but it does use several types of UI elements, like text, an image and a button.

First, open the starter project for this chapter in Unity. Create a new empty scene by right-clicking the RW / Scenes folder in the Project view and selecting Create ▸ Scene. Name this new scene Title and double-click the scene asset to open it in the editor.

When adding a new scene to your game, it’s good practice to add it to the Scenes list in the Build Settings because that includes the scene in the final game. Not doing this will result in errors when you try to load the scene.

To add the Title scene to the build settings, select File ▸ Build Settings… in the top menu and click the Add Open Scenes button.

Next, close the Build Settings window; it’s time to get the scene ready.

Take a look around the editor. You’ll see a beautiful blue sky in both the Scene and Game views. Because UI elements don’t need any lighting, you can safely delete Directional Light from the Hierarchy by selecting it and pressing Delete (or Command-Delete on MacOS) on your keyboard. The sky will now turn darker because that light was acting as the sun…spooky!

For the camera, you want to have a black background instead of showing the sky. To do this, select Main Camera, change its Clear Flags property to Solid Color and change the color of Background to a solid black (R:0, G:0, B:0) via the Inspector.

Perfect! Now you have an empty void that’s begging to be filled with UI elements.

Canvas

Unlike the GameObjects you’ve seen until now, UI elements can’t be placed just anywhere in the Hierarchy — they need to be children of a canvas. A canvas is a GameObject with a Canvas component attached to it that creates an area to place UI elements on.

Rect Transform component

Canvas component

Canvas Scaler component

Graphic Raycaster component

Adding UI elements

Time to get down to business! The first UI element you’ll need to add is the title itself at the top. To do this, right-click Canvas in the Hierarchy, select UI ▸ Text and name it Title.

Text

The very first component is a Rect Transform, which can be edited this time. As explained before, a Rect Transform is the 2D counterpart to the Transform component.

Image

Now that the title text is done, it’s time to add the logo in the middle of the screen. Right-click Canvas in the Hierarchy and select UI ▸ Image. Name this new image Logo, and look to the Inspector. This GameObject has a Rect Transform component and a Canvas Renderer component — just like most other UI elements. There’s an Image component attached, as well.

Button

Right-click Canvas again, select UI ▸ Button to add a button and name it New Game Button. Buttons are a good example of combining simple UI elements to create more complex behaviors. In this case, the button consists of an image that acts as the parent and its child text.

Interaction system

Open the dining hall scene by double-clicking DiningHall in RW / Scenes. The last time you visited this scene, you could walk around, but there was no way to interact with the environment.

Adding a user interface for interactions

Your goal is to add a window with some text — like the one pictured below — and extend the interaction system. The process is very similar to what you did with the title screen.

using UnityEngine.UI;
public GameObject interactionWindow;
public Text interactionText;
if (closest != null)
{
    interactionTarget = closest.GetComponent<InteractableObject>();
    // A
}
else
{
    interactionTarget = null;
    // B
}
if (!interactionWindow.activeSelf) // 1
{
    interactionWindow.SetActive(true); // 2
}
interactionText.text = interactionTarget.interactionVerb
    + " " + interactionTarget.interactionName; // 3
if (interactionWindow.activeSelf)
{
    interactionWindow.SetActive(false);
}

Key points

  • UI elements need to be children of a Canvas.
  • A Canvas component creates an area to place UI elements on.
  • The EventSystem passes input to the canvas.
  • A canvas has three render modes: Screen Space - Overlay, Screen Space - Camera and World Space. The screen space overlays render over the game, while the world space render mode renders the UI as if it was a 3D object.
  • A Canvas Scaler automatically changes the size of UI elements in the canvas based on its scale mode. The easiest mode to work with is Scale With Screen Size.
  • Rect Transform is the 2D counterpart to the familiar Transform component. It sets the position, size and anchor points of a UI element.
  • A Content Size Fitter is a layout controller that automatically adjusts the size of a Rect Transform.
  • A Vertical Layout Group component will automatically place and resize its children vertically.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now