Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Unity 2021 Cookbook
Unity 2021 Cookbook

Unity 2021 Cookbook: Over 140 recipes to take your Unity game development skills to the next level , Fourth Edition

eBook
€8.99 €32.99
Paperback
€32.99 €41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Unity 2021 Cookbook

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

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:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Discover the latest features of Unity 2021 including coverage of AR/VR development
  • Follow practical recipes for better 2D and 2D character development with Unity GameKits
  • Learn powerful techniques and expert best practices in building 3D objects, textures, and materials

Description

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.

Who is this book for?

If you’re a Unity developer looking for better ways to resolve common recurring problems with recipes, then this book is for you. Programmers dipping their toes into multimedia features for the first time will also find this book useful. Before you get started with this Unity engine book, you’ll need a solid understanding of Unity’s functionality and experience with programming in C#.

What you will learn

  • Discover how to add core game features to your projects with C# scripting
  • Create powerful and stylish UI with Unity's UI system, including power bars, radars, and button-driven scene changes
  • Work with essential audio features, including background music and sound effects
  • Discover Cinemachine in Unity to intelligently control camera movements
  • Add visual effects such as smoke and explosions by creating and customizing particle systems
  • Understand how to build your own Shaders with the Shader Graph tool

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 06, 2021
Length: 816 pages
Edition : 4th
Language : English
ISBN-13 : 9781839219276
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 06, 2021
Length: 816 pages
Edition : 4th
Language : English
ISBN-13 : 9781839219276
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 100.97 127.97 27.00 saved
Learning C# by Developing Games with Unity 2021
€41.99 €52.99
Hands-On Unity 2021 Game Development
€25.99 €32.99
Unity 2021 Cookbook
€32.99 €41.99
Total 100.97 127.97 27.00 saved Stars icon
Visually different images

Table of Contents

15 Chapters
Displaying Data with Core UI Elements Chevron down icon Chevron up icon
Responding to User Events for Interactive UIs Chevron down icon Chevron up icon
Inventory and Advanced UIs Chevron down icon Chevron up icon
Inventory and Advanced UIs
Technical requirements
Creating a simple 2D mini-game – SpaceGirl
Getting ready
How to do it...
How it works...
Displaying single object pickups with carrying and not-carrying text
Getting ready
How to do it...
How it works...
The PlayerInventory script class
The PlayerInventoryDisplay script class
There's more...
Collecting multiple items and display the total number carried
Alternative – combining all the responsibilities into a single script
Displaying single-object pickups with carrying and not-carrying icons
Getting ready
How to do it...
How it works...
Displaying multiple pickups of the same object with multiple status icons
Getting ready
How to do it...
How it works...
There's more...
Revealing icons for multiple object pickups by changing the size of a tiled image
Using panels to visually outline the inventory UI area and individual items
Getting ready
How to do it...
How it works...
Creating a C# inventory slot UI to display scripted components
Getting ready
How to do it...
How it works...
There's more...
Modifying the game for a second inventory panel for keys
Using UI Grid Layout Groups to automatically populate a panel
Getting ready
How to do it...
How it works...
There's more...
Automatically inferring the number of inventory slots based on the number of GameObjects tagged Star
Adding a horizontal scroll bar to the inventory slot display
Automatically changing the grid cell size based on the number of slots in the inventory
Displaying multiple pickups of different objects as a list of text via a dynamic list of scripted PickUp objects
Getting ready
How to do it...
How it works...
There's more...
Ordering items in the inventory list alphabetically
Using a Dictionary and Enums to display text totals for different objects
Getting ready
How to do it...
How it works...
Creating a runtime UI Toolkit interface
Getting ready
How to do it...
How it works...
Further reading
Playing and Manipulating Sounds Chevron down icon Chevron up icon
Creating 3D Objects, Terrains, Textures, and Materials Chevron down icon Chevron up icon
2D Animation and Physics Chevron down icon Chevron up icon
Characters, Game Kits, and Starter Assets Chevron down icon Chevron up icon
Web Server Communication and Online Version Control Chevron down icon Chevron up icon
Controlling and Choosing Positions Chevron down icon Chevron up icon
Navigation Meshes and Agents Chevron down icon Chevron up icon
Cameras and Rendering Pipelines Chevron down icon Chevron up icon
Shader Graphs and Video Players Chevron down icon Chevron up icon
Advanced Topics - Gizmos, Automated Testing, and More Chevron down icon Chevron up icon
Advanced Topics - Gizmos, Automated Testing, and More
Technical requirements
Using Gizmo to show the currently selected object in the Scene window
How to do it...
How it works...
See also
Creating an editor snap-to-grid drawn by a Gizmo
How to do it...
How it works...
There's more...
Saving and loading player data – using static properties
Getting ready
How to do it...
How it works...
There's more...
Hiding the score before the first attempt is completed
See also
Saving and loading player data – using PlayerPrefs
Getting ready
How to do it...
How it works...
See also
Loading game data from a text file map
Getting ready
How to do it...
How it works...
Saving data to a file while the game is running
How to do it...
How it works...
See also
Generating and running a default test script class
How to do it...
How it works...
There's more...
Creating a default test script from the Project window's Create menu
Edit mode minimum skeleton unit test script
A simple unit test
How to do it...
How it works...
There's more...
Shorter tests with values in the assertion
Expected value followed by the actual value
Parameterizing tests with a data provider
How to do it...
How it works...
Unit testing a simple health script class
How to do it...
How it works...
Health.cs
TestHealth.cs
Creating and executing a unit test in PlayMode
How to do it...
How it works...
PlayMode testing a door animation
Getting ready
How to do it...
How it works...
There's more...
PlayMode and unit testing a player health bar with events, logging, and exceptions
Getting ready
How to do it...
How it works...
PlayMode testing
Unit tests
See also
Reporting Code Coverage testing
Getting ready
How to do it...
How it works...
Running simple Python scripts inside Unity
How to do it...
How it works...
Further reading
Particle Systems and Other Visual Effects Chevron down icon Chevron up icon
Virtual and Augmented Reality (VR/AR) Chevron down icon Chevron up icon
Virtual and Augmented Reality (VR/AR)
Technical requirements
Setting up Unity for VR
How to do it...
How it works...
Setting up an Oculus Quest/2 in Developer Mode
Getting ready
How to do it...
How it works...
Creating a VR project for the Oculus Quest/2
Getting ready
How to do it...
How it works...
There's more...
Build failure due to Android version
Build failure due to "namespace cannot be found" error
Sideloading APK files to an Android device (such as the Quest headset)
Creating a VR project using the Mock HMD device
Getting ready
How to do it...
How it works...
Working with the Mozilla demo WebXR project
Getting ready
How to do it...
How it works...
There's more...
Using GitHub Pages to publish your WebXR project for free
Learning more about the WebXR example project
Fixing pink (shader/material) problems
The community maintaining more up-to-date XR resources
Fixing obsolete code errors
Adding 360-degree videos to a VR project
Getting ready
How to do it...
How it works...
There's more...
Playing 360-degree videos on the surface of a 3D object
Exploring the Unity AR samples
Getting ready
How to do it...
How it works...
There's more...
Targeting iOS device builds
Allowing Android APK file downloads on your phone
Setting up Unity for AR
How to do it...
How it works...
There's more...
Build failure due to Android version
Build failure due to Vulkan API graphics settings
Creating a simple AR Foundation project
Getting ready
How to do it...
How it works...
Detecting and highlighting planes with AR Foundation
Getting ready
How to do it...
How it works...
Creating an AR furniture previewer by detecting horizontal planes
Getting ready
How to do it...
How it works...
Creating a floating 3D model over an image target
Getting ready
How to do it...
How it works...
Further reading

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(10 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Abey Campbell Sep 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've been lecturing Virtual and Augmented Reality and Games Development courses for many years in University College Dublin . The cookbook has been great help to point to when I have students that feel they need to have a step by step walkthrough that has ready to go solutions to common problems that students ( and even some Professors too) find when starting to develop on Unity. I recommend the book to any student and any aspiring game developer.Assistant Professor Abraham Campbell, University College Dublin
Amazon Verified review Amazon
Peter Lynch Sep 28, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A great read for novices and experienced game developers. Programming a game requires knowledge of UI, audio, animation, navigation, rendering, physics and so many other components. Even if you are familiar with a game engine, you will not remember everything. So instead of having to create your own code snippets book, this one does it for you. Lots of really useful code listing for tasks regularly done in a game such as UIs, event management, inventory, audio, camera, navigation and communicating with a backend server. You can also download the code if you don’t want to type it in, though I think you learn more doing it this way. It is delivered in an easy-to-read format with useful Unity editor screenshots to assist the reader. It is up to date and covers the latest version of Unity at the time of this review. Highly recommended.Peter LynchGame Developer – Fierce Fun
Amazon Verified review Amazon
James McCarthy Dec 16, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
After purchasing any number of Unity courses over the years, but never seeming to finish anything, this book boosted my Unity skills and my productivity right away. Downloadable source files plus the "how to do it", "How it works", and "There's more" teaching style makes this an essential resource.
Amazon Verified review Amazon
00akgl Jan 03, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is really detailed and has so many recipes to follow, so we need to have basic knowledge of Unity.
Amazon Verified review Amazon
Lauren Nov 17, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been studying and using Unity over the past 3 years, this book is a fantastic collection of recipes that can be used to help create and elevate your Unity game. This cookbook contains extremely valuable resources such as scripts, recipes and projects to guide you along when using Unity and developing games/ assets.This is the second edition of the book I have purchased, this latest edition has been updated to keep up with Unity's latest features and updates. Whether you would like to start using Unity as a beginner, or if you are looking to upskill, this cookbook will not disappoint.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.