Unity 2021 Cookbook - Fourth Edition

By Matt Smith , Shaun Ferns
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Responding to User Events for Interactive UIs
About this book

If you are a Unity developer looking to explore the newest features of Unity 2021 and recipes for advanced challenges, then this fourth edition of Unity Cookbook is here to help you.

With this cookbook, you’ll work through a wide variety of recipes that will help you use the essential features of the Unity game engine to their fullest potential. You familiarize yourself with shaders and Shader Graph before exploring animation features to enhance your skills in building games.

As you progress, you will gain insights into Unity's latest editor, which will help you in laying out scenes, tweaking existing apps, and building custom tools for augmented reality and virtual reality (AR/VR) experiences. The book will also guide you through many Unity C# gameplay scripting techniques, teaching you how to communicate with database-driven websites and process XML and JSON data files.

By the end of this Unity book, you will have gained a comprehensive understanding of Unity game development and built your development skills. The easy-to-follow recipes will earn a permanent place on your bookshelf for reference and help you build better games that stay true to your vision.

Publication date:
September 2021
Publisher
Packt
Pages
816
ISBN
9781839217616

 
Displaying Data with Core UI Elements

A key element that contributes to the entertainment and enjoyment of most games is the quality of the visual experience, and an important part of this is the user interface (UI). UI elements involve ways for the user to interact with the game (such as buttons, cursors, and text boxes), as well as ways for the game to present up-to-date information to the user (such as the time remaining, current health, score, lives left, or location of enemies). This chapter is filled with UI recipes to give you a range of examples and ideas for creating game UIs.

Every game and interactive multimedia application is different, and so this chapter attempts to fulfill two key roles:

  • The first aim is to provide step-by-step instructions on how to create a range of Unity 2021 basic UI elements and, where appropriate, associate them...
 

Technical requirements

For this chapter, you will need Unity 2021.1 or later, plus one of the following:

  • Microsoft Windows 10 (64-bit)/GPU: DX10, DX11, and DX12-capable
  • macOS Sierra 10.12.6+/GPU Metal-capable Intel or AMD
  • Linux Ubuntu 16.04, Ubuntu 18.04, and CentOS 7/GPU: OpenGL 3.2+ or Vulkan-capable, Nvidia or AMD

For each chapter, there is a folder that contains the asset files you will need in this book's GitHub repository at https://github.com/PacktPublishing/Unity-2021-Cookbook-Fourth-Edition.

 

Displaying a "Hello World" UI text message

The first traditional problem to be solved with new computing technology is to display the Hello World message, as shown in the following screenshot: 

Figure 1.3  Displaying the "Hello World" message

In this recipe, you'll learn how to create a simple UI text object with this message, in large white text with a selected font, in the center of the screen.

 

Getting ready

For this recipe, we have prepared the font that you need in a folder named Fonts in the 01_01 folder. 

 

How to do it...

To display a Hello World text message, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided Fonts folder, as described in the Getting ready section. Copy these font files into your Unity project – they need to be in your Assets folder.
  1. In the Hierarchy window, add a Text GameObject to the scene by going to GameObject | UI | Text. Name this GameObject Text-hello.
Alternatively, you can use the Create menu immediately below the Hierarchy tab. To do so, go to Create | UI | Text.
  1. Ensure that your new Text-hello GameObject is selected in the Hierarchy window.
    Now, in
    the Inspector window, ensure the following properties are set:
    • Text set to read Hello World
    • Font set to Xolonium-Bold
    • Font Size as per your requirements (large – this depends on your screen; try 50 or 100)
    • Alignment set to horizontal and vertical-center
    • Horizontal and Vertical Overflow set to Overflow
    • Color set to white

The following screenshot...

 

How it works...

In this recipe, you added a new Text-hello GameObject to the scene. A parent Canvas and UI EventSystem will have also been automatically created. Also, note that by default, a new UI GameObject is added to the UI Layer – we can see this illustrated at the top right of the Inspector window in Figure 1.4. This is useful since, for example, it is easy to hide/reveal all UI elements by hiding/revealing this layer in the Culling Mask property of the Camera component of the Main Camera GameObject.

You set the text content and presentation properties and used the Rect Transform anchor presets to ensure that whatever way the screen is resized, the text will stay horizontally and vertically centered.

 

There's more...

Here are some more details you don't want to miss.

 

Styling substrings with rich text

Each separate UI Text component can have its own color, size, boldness styling, and so on. However, if you wish to quickly add a highlighting style to the part of a string to be displayed to the user, you can apply HTML-style markups. The following are examples that are available without the need to create separate UI text objects:

  • Change the font to Xolonium-Regular
  • Embolden text with the b markup: I am <b>bold</b>
  • Italicize text with the i markup: I am <i>italic</i>
  • Set the text color with hex values or a color name: I am a <color=green>green text </color>, but I am <color=#FF0000>red</color>
You can learn more by reading the Unity online manual's Rich Text page at http://docs.unity3d.com/Manual/StyledText.html.
 

Displaying a digital clock

Whether it is real-world time or an in-game countdown clock, many games are enhanced by some form of clock or timer display. The following screenshot shows the kind of clock we will be creating in this recipe:

Figure 1.6  Displaying a digital clock when the scene is run

The most straightforward type of clock to display is a string composed of the integers for hours, minutes, and seconds, which is what we'll create in this recipe.

 

Getting ready

For this recipe, we have prepared the font that you will need in a folder named Fonts in the 01_01 folder. 

 

How to do it...

To create a digital clock, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided Fonts folder, as described in the Getting ready section. Copy these font files into your Unity project they need to be in your Assets folder.
  3. In the Hierarchy window, add a UI Text GameObject to the scene named Text-clock.
  1. Ensure that the Text-clock GameObject is selected in the Hierarchy window. Now, in the Inspector window, ensure that the following properties are set:
    • Font Type set to Xolonium Bold
    • Font Size set to 20
    • Alignment set to horizontal and vertical-center
    • Horizontal and Vertical Overflow settings set to Overflow
    • Color set to white
  1. In Rect Transform, click on the Anchor Presets square icon, which will result in the appearance of several rows and columns of preset position squares. Hold down Shift Alt and click on the top and center column rows.
  2. In the Project window, create a folder named _Scripts...
 

How it works...

In this recipe, you added a Text GameObject to a scene. Then, you added an instance of the ClockDigital C# script class to that GameObject.

Notice that as well as the standard two C# packages (UnityEngine and System.Collections) that are written by default for every new script, you added the using statements to two more C# script packages, UnityEngine.UI and System. The UI package is needed since our code uses the UI text object, and the System package is needed since it contains the DateTime class that we need to access the clock on the computer where our game is running.

There is one variable, textClock, which will be a reference to the Text component, whose text content we wish to update in each frame with the current time in hours, minutes, and seconds.

The Awake() method (executed when the scene begins) sets the textClock variable to be a reference to the Text component in the GameObject, to which our scripted object has been added. Storing a reference to a component...

 

Displaying a digital countdown timer

As a game mechanic, countdown clocks are a popular feature in many games:

Figure 1.8 – Countdown clock

This recipe, which will adapt the digital clock shown in the previous recipe, will show you how to display a digital countdown clock that will count down from a predetermined time to zero in Figure 1.8.

 

Getting ready

This recipe adapts to the previous one. So, make a copy of the project for the previous recipe, and work on this copy.

For this recipe, we have prepared the script that you need in a folder named _Scripts inside the 01_03 folder. 

 

How to do it...

To create a digital countdown timer, follow these steps:

  1. Import the provided _Scripts folder.
  2. In the Inspector window, remove the scripted component, ClockDigital, from the Text-clock GameObject. You can do this by choosing Remove Component from the 3-dot options menu icon for this component the Inspector window. 
  3. In the Inspector window, add an instance of the CountdownTimer script class as a component by clicking the Add Component button, selecting Scripts, and choosing the CountdownTimer script class.
  1. Create a DigitalCountdown C# script class that contains the following code, and add an instance as a scripted component to the Text-clock GameObject:
using UnityEngine; 
using UnityEngine.UI; 

public class DigitalCountdown : MonoBehaviour { 
   private Text textClock; 
   private CountdownTimer countdownTimer; 

   void Awake() { 
         textClock = GetComponent<Text>(); 
         countdownTimer...
 

How it works...

In this recipe, you added instances of the DigitalCountdown and CountdownTimer C# script classes to your scene's UI Text GameObject.

The Awake() method caches references to the Text and CountdownTimer components in the countdownTimer and textClock variables. The textClock variable will be a reference to the UI Text component, whose text content we wish to update in each frame with a time-remaining message (or a timer-complete message).

The Start() method calls the countdown timer object's CountdownTimerReset(...) method, passing an initial value of 30 seconds.

The Update() method is executed in every frame. This method retrieves the countdown timer's remaining seconds and stores this value as an integer (whole number) in the timeRemaining variable. This value is passed as a parameter to the TimerMessage()  method, and the resulting message is stored in the string (text) variable message. Finally...

 

Creating a message that fades away

Sometimes, we want a message to only be displayed for a certain time, and then fade away and disappear. This recipe will describe the process for displaying an image and then making it fade away completely after 5 seconds. It could be used for providing instructions or warnings to a player that disappears so as not to take up screen space.

 

Getting ready

This recipe adapts the previous one. So, make a copy of the project for that recipe and work on this copy.

 

How to do it...

To display a text message that fades away, follow these steps:

  1. In the Inspector window, remove the scripted component, DigitalCountdown, from the Text-clock GameObject.
  1. Create a C# script class called FadeAway that contains the following code, and add an instance as a scripted component to the Text-hello GameObject:
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(CountdownTimer))]
public class FadeAway : MonoBehaviour
{
private CountdownTimer countdownTimer;
private Text textUI;

void Awake()
{
textUI = GetComponent<Text>();
countdownTimer = GetComponent<CountdownTimer>();
}

void Start()
{
countdownTimer.ResetTimer(5);
}

void Update()
{
float alphaRemaining =
countdownTimer.GetProportionTimeRemaining();
print(alphaRemaining);
Color c = textUI.color;
c.a = alphaRemaining;
textUI.color = c;
}
}
  1. When you run the scene, you...
 

How it works...

In this recipe, you added an instance of the FadeAway scripted class to the Text-hello GameObject. Due to the RequireComponent(...) attribute, an instance of the CountdownTimer script class was also automatically added.

The Awake() method caches references to the Text and CountdownTimer components in the countdownTimer and textUI variables.

The Start() method reset the countdown timer so that it starts counting down from 5 seconds.

The Update() method (executed every frame) retrieves the proportion of time remaining in our timer by calling the GetProportionTimeRemaining() method. This method returns a value between 0.0 and 1.0, which also happens to be the range of values for the alpha (transparency) property of the color property of a UI Text GameObject.

Flexible range of 0.01.0.

It is often a good idea to represent proportions as values between 0.0 and 1.0. Either this will be just the value we want for...

 

Displaying a perspective 3D Text Mesh

Unity provides an alternative way to display text in 3D via the Text Mesh component. While this is really suitable for a text-in-the-scene kind of situation (such as billboards, road signs, and the general wording on the side of 3D objects that might be seen close up), it is quick to create and is another way of creating interesting menus or instruction scenes.

In this recipe, you'll learn how to create scrolling 3D text, simulating the famous opening credits of the movie Star Wars, which looks something like this:

Figure 1.9 – Scrolling 3D text
 

Getting ready

For this recipe, we have prepared the fonts that you need in a folder named Fonts, and the text file that you need in a folder named Text, both of which can be found inside the 01_05 folder. 

 

How to do it...

To display perspective 3D text, follow these steps:

  1. Create a new Unity 3D project. This will ensure that we start off with a Perspective camera, suitable for the 3D effect we want to create.
If you need to mix 2D and 3D scenes in your project, you can always manually set any camera's Camera Projection property to Perspective or Orthographic via the Inspector window.
  1. In the Hierarchy window, select the Main Camera item and, in the Inspector window, set its properties as follows: Camera Clear Flags to Solid colorBackground color to Black, and Field of View to 150.
  2. Import the provided Fonts and Text folders.
  3. In the Hierarchy window, add a UI | Text GameObject to the scene by going to GameObject | UI | Text. Name this GameObject Text-star-wars.
  4. Set the UI Text Text-star-wars GameObject's Text Content to Star Wars (with each word on a new line). Then, set its Font to Xolonium Bold, its Font Size to 50, and...
 

How it works...

In this recipe, you simulated the opening screen of Star Wars, with a flat UI text object title at the top of the screen and a 3D Text Mesh with settings that appear to be disappearing into the horizon with 3D perspective "squashing."

 

There's more...

There are some details you don't want to miss.

 

Making the text crawl as it does in the movie

With a few lines of code, we can make this text scroll in the horizon, just as it does in the movie. Add the following C# script class, called ScrollZ, as a component of the Text-crawler GameObject:

using UnityEngine;
using System.Collections;

public class ScrollZ : MonoBehaviour
{
// variable letting us change how fast we'll move text into the 'distance'
public float scrollSpeed = 20;

//-----------------
void Update ()
{
// get current position of parent GameObject
Vector3 pos = transform.position;

// get vector pointing into the distance
Vector3 localVectorUp = transform.TransformDirection(0,1,0);

// move the text object into the distance to give our 3D scrolling effect
pos += localVectorUp * scrollSpeed * Time.deltaTime;
transform.position = pos;
}
}

In each frame, via the Update() method, the position of the 3D text object is moved in the direction of this GameObject's local up direction...

 

Where to learn more

You can learn more about 3D Text and Text Meshes in the Unity online manual at http://docs.unity3d.com/Manual/class-TextMesh.html.

An alternative way of achieving perspective text like this would be to use a Canvas with the World Space render mode.
 

Creating sophisticated text with TextMeshPro

In 2017, Unity purchased the TextMeshPro Asset Store product and has integrated it into Unity as a free core feature. TextMeshPro uses a Signed Distance Field (SDF) rendering method, resulting in clear and sharply drawn characters at any point size and resolution. You will need them, but it's easy to create them. Just use the ones provided for now and let's focus on something else.

 

Getting ready

For this recipe, we have prepared the fonts that you need in a folder named Fonts & Materials inside the 01_06 folder.

 

How to do it...

To display a text message with sophisticated TextMeshPro visual styling, follow these steps:

  1. Create a new Unity 3D project.
  1. Add a new UI TextMeshPro Text GameObject in the scene by going to GameObject | UI | TextMeshPro  Text. Name this GameObject Text-sophisticated. Choose Import TMP Essentials if prompted.
TextMeshPro GameObjects do not have to be part of the UI Canvas. You can add a TextMeshPro GameObject to the scene directly by choosing Create | 3D Object | TextMeshPro  Text from the Scene window.
  1. Ensure that your new Text-sophisticated GameObject is selected in the Hierarchy window. In the Inspector window for Rect Transform, click on the Anchor Presets square icon, hold down Shift + Alt, and click on the top and stretch rows.
  2. Ensure the following properties are set:

Font Settings:

  • Font Asset set to Anton SDF
  • Material Preset set to Anton SDF - Outline
  • Font size set to 200
  • Alignment set...
 

How it works...

In this recipe, you added a new UI Text TextMeshPro GameObject to a scene. You chose one of the SDF fonts and an outline material preset. You then adjusted the settings for the face (the inner part of each character), outline, and drop shadow (Underlay).

There are hundreds of settings for the TextMeshPro component, which means much experimentation may be required to achieve a particular effect.

 

There's more...

Here are some more details you don't want to miss.

 

Rich text substrings for colors, effects, and sprites

TextMeshPro offers over 30 HTML-style markups for substrings. The following code illustrates some:

<sprite=5> inline sprite graphics 

<smallcaps>...</smallcaps> small-caps and colors 

<#ffa000>...</color> substring colors 

One powerful piece of markup is the <page> tag, which allows a single set of text to be made interactive and presented to the user as a sequence of pages.

You can learn more by reading the online manual Rich Text page at http://digitalnativestudios.com/textmeshpro/docs/rich-text/.

 

Displaying an image

There are many cases where we wish to display an image onscreen, including logos, maps, icons, and splash graphics. In this recipe, we will display an image centered at the top of the screen.

The following screenshot shows Unity displaying an image:

Figure 1.11 – Displaying the Unity logo as an image
 

Getting ready

For this recipe, we have prepared the image that you need in a folder named Images in the 01_07 folder. 

 

How to do it...

To display an image, follow these steps:

  1. Create a new Unity 2D project.
  2. Set the Game window to 400 x 300. Do this by displaying the Game window, and then creating a new Resolution in the drop-down menu at the top of the panel.
  3. Click the plus (+) symbol at the bottom of this menu, setting Label to Core UI, Width to 400, and Height to 300. Click OK; the Game window should be set to this new resolution:

Figure 1.12  Adding a new screen Resolution to the Game window
Alternatively, you can set the default Game window's resolution by going to Edit | Project Settings | Player and then the width and height of Resolution and Presentation in the Inspector window (having turned off the Full-Screen option).
  1. Import the provided Images folder. In the Inspector window, ensure that the unity_logo image has Texture Type set to Default. If it has some other type, then choose Default from the drop...
 

How it works...

In this recipe, you ensured that an image has its Texture Type set to Default. You also added a UI RawImage control to the scene. The RawImage control has been made to display the unity_logo image file. This image has been positioned at the top-center of the Game window.

 

There's more...

Here are some details you don't want to miss.

 

Working with 2D sprites and UI Image components

If you simply wish to display non-animated images, then Texture images and UI RawImage controls are the way to go. However, if you want more options regarding how an image should be displayed (such as tiling and animation), the UI Image control should be used instead. This control needs image files to be imported as the Sprite (2D and UI) type.

Once an image file has been dragged into the UI Image control's Sprite property, additional properties will be available, such as Image Type, and options to preserve the aspect ratio.

If you wish to prevent a UI Sprite GameObject from being distorted and stretched, go to the Inspector window and check the Preserve Aspect option in its Image (Script) component.

 

See also

An example of tiling a sprite image can be found in the Revealing icons for multiple object pickups by changing the size of a tiled image recipe in Chapter 3, Inventory UIs and Advanced UIs.

 

Creating UIs with the Fungus open source dialog system

Rather than constructing your own UI and interactions from scratch each time, there are plenty of UI and dialogue systems available for Unity. One powerful, free, and open source dialog system is called Fungus, which uses a visual flowcharting approach to dialog design:

 

Figure 1.14 – An example of dialogue generated by Fungus

In this recipe, we'll create a very simple, one-sentence piece of dialogue to illustrate the basics of Fungus. The preceding screenshot shows the Fungus-generated dialog for the sentence How are you today?.

 

How to do it...

To create a one-sentence piece of dialog using Fungus, follow these steps:

  1. Create a new Unity 2D project and ensure you are logged into your Unity account in the Unity Editor.
  2. Open the Unity asset store in a web browser and log into your Unity account on the Asset Store.
  3. On the Asset Store website, search for Fungus Games and select this asset. Click on Add to My Assets. Then, after the tab changes, click on Open in Unity.
  4. In your Unity Editor, the Package Manager panel should open, and the Fungus assets should be selected in the list of My Assets. Click Download. Once they've been downloaded, click Import.
  5. In the Project window, you should now see two new folders named Fungus and FungusExamples.
  6. Create a new Fungus Flowchart GameObject by going to Tools | Fungus | Create | Flowchart.
  1. In the Hierarchy window, select the new Flowchart GameObject. Then, in the Inspector window, click the Open Flowchart Window button. A new Fungus Flowchart...
 

How it works...

In this recipe, you created a new Unity project and imported the Fungus asset package, which contains the Fungus Unity menus, windows, and commands, as well as the example projects.

Then, you added a Fungus Flowchart to your scene with a single block that you named Start. Your block starts to execute when the game begins (since the default for the first block is to be executed upon receiving the Game Started event).

In the Start block, you added a sequence of two Say commands. Each command presents a sentence to the user and then waits for the continue button to be clicked before proceeding to the next command.

As can be seen, the Fungus system handles the work of creating a nicely presented panel to the user, displaying the desired text and the Continue button. Fungus offers many more features, including menus, animations, and controls for sounds and music, the details of which can be found in the next recipe and by exploring their provided example projects and their...

 

Creating a Fungus character dialog with images

The Fungus dialog system that we introduced in the previous recipe supports multiple characters, whose dialogs can be highlighted through their names, colors, sound effects, and even portrait images. In this recipe, we'll create a two-character dialog between Sherlock Holmes and Watson to illustrate the system:

Figure 1.18 – Highlighting the speaking character by name, color, and portrait image
 

How to do it...

To create a character dialog with portrait images using Fungus, follow these steps:

  1. Create a new Unity 2D project.
  2. Open the Asset Store window, Import the Fungus dialogue asset package (this includes the Fungus examples, whose images we'll use for the two characters).
  1. Create a new Fungus Flowchart GameObject by going to Tools | Fungus | Create | Flowchart.
  2. Display and dock the Fungus Flowchart window.
  3. Change the name of the only block in Flowchart to The case of the missing violin.
  4. Create a new character by going to Tools | Fungus | Create | Character.
  5. You should now see a new Character GameObject in the Hierarchy window.
  6. With the Character 1 GameObject selected in the Project window, edit its properties in the Inspector window, like so:
    • Rename this GameObject Character 1 – Sherlock.
    • In its Character(Script) component, set Name Text to Sherlock and Name Color to green.
    • In the Inspector window click...
 

How it works...

In this recipe, you created a new Unity project with the Fungus asset package.

You then added a Fungus Flowchart to your scene, and also added two characters (each with a text color and a portrait image).

For the block in the Flowchart, you added two Say commands, stating which character was saying each sentence and which portrait to use (if you had added more portrait images, you could have selected different images to indicate the emotion of the character speaking).

 

There's more...

Fungus offers a data-driven approach to conversations. The character and portrait (facing direction, movement onto and off the stage, and so on) can be defined through text in a simple format by using the Say command's Narrative | Conversation option. This recipe's conversation with portrait images can be declared with just two lines of text in a Conversation:

Sherlock confident: Watson, have you seen my violin?
John annoyed: No, why don't you find it yourself using your amazing powers of deduction...

You can learn more about the Fungus conversation system by reading their documentation pages: https://github.com/snozbot/fungus/wiki/conversation_system.

 

Further reading

The following are some useful resources for learning more about working with core UI elements in Unity:

About the Authors
  • Matt Smith

    Matt Smith is computing academic at TUDublin (Technological University of Dublin) Ireland, where he leads the DRIVE Research Group (Digital Realities, Interaction, and Virtual Environments). Matt started computer programming on a brand new ZX80 and submitted 2 games for his computing O-level exam. After nearly 10 years as a full-time student on a succession of scholarships, he gained several degrees in computing, including a Ph.D. in computational musicology. In 1985, Matt wrote the lyrics and was in the band whose music appeared on the audio cassette carrying the computer game Confuzion. Matt is a documentation author for the open-source Unity Fungus visual scripting and dialogue system.

    Browse publications by this author
  • Shaun Ferns

    Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.

    Browse publications by this author
Unity 2021 Cookbook - Fourth Edition
Unlock this book and the full library FREE for 7 days
Start now