Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Unity 2018 Cookbook
Unity 2018 Cookbook

Unity 2018 Cookbook: Over 160 recipes to take your 2D and 3D game development to the next level , Third Edition

Arrow left icon
Profile Icon Matt Smith Profile Icon Francisco Queiroz
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7 (3 Ratings)
Paperback Aug 2018 794 pages 3rd Edition
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Matt Smith Profile Icon Francisco Queiroz
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7 (3 Ratings)
Paperback Aug 2018 794 pages 3rd Edition
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unity 2018 Cookbook

Displaying Data with Core UI Elements

In this chapter, we will cover:

  • Displaying a "Hello World" UI text message
  • Displaying a digital clock
  • Displaying a digital countdown timer
  • Creating a message that fades away
  • Displaying a perspective 3D Text Mesh
  • Creating sophisticated text with TextMeshPro
  • Displaying an image
  • Creating UIs with the Fungus open source dialog system
  • Creating a Fungus character dialog with images

Introduction

A key element contributing 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.

The big picture

Every game 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 the Unity 2018 basic UI elements and, where appropriate, associate them with game variables in code. The second aim is to provide a rich illustration of how UI elements can be used for a variety of purposes so that you can get good ideas about how to make the Unity UI set of controls deliver the particular visual experience and interactions for the games that you are developing.

The basic UI elements can provide static images and text to just make the screen look more interesting. By using scripts, we can change the content of these images and text objects, so that the players' numeric scores can be updated, or we can show stickmen images to indicate how many lives the player has left. Other UI elements are interactive, allowing users to click on buttons, choose options, enter text, and so on. More sophisticated kinds of UI can involve collecting and calculating data about the game (such as percentage time remaining or enemy hit damage; or the positions and types of key GameObjects in the scene, and their relationship to the location and orientation of the player), and then displaying these values in a natural, graphical way (such as progress bars or radar screens).

Core GameObjects, components, and concepts relating to Unity UI development include:

  • Canvas: Every UI element is a child to a Canvas. There can be multiple Canvas GameObjects in a single scene. If a Canvas is not already present, then one will automatically be created when a new UI GameObject is created, with that UI object as the child to the new Canvas GameObject.
  • EventSystem: An EventSystem GameObject is required to manage the interaction events for UI controls. One will automatically be created with the first UI element. Unity generally only allows one EventSystem in any Scene (some proposed code for multiple event systems can be found at https://bitbucket.org/Unity-Technologies/ui/pull-requests/18/support-for-multiple-concurrent-event/diff)
  • Visual UI controls: The visible UI controls themselves include Button, Image, Text, and Toggle.
  • The Rect Transform component: UI GameObjects can exist in a different space from that of the 2D and 3D scenes, which cameras render. Therefore, UI GameObjects all have the special Rect Transform component, which has some different properties to the scene's GameObject Transform component (with its straightforward X/Y/Z position, rotation, and scale properties). Associated with Rect Transforms are pivot points (reference points for scaling, resizing, and rotations) and anchor points.

The following diagram shows the four main categories of UI controls, each in a Canvas GameObject and interacting via an EventSystem GameObject. UI Controls can have their own Canvas, or several UI controls can be in the same Canvas. The four categories are: static (display-only) and interactive UI controls, non-visible components (such as ones to group a set of mutually exclusive radio buttons), and C# script classes to manage UI-control behavior through logic written in the program code. Note that UI controls that are not a child or descendant of a Canvas will not work properly, and interactive UI controls will not work properly if the EventSystem is missing. Both the Canvas and EventSystem GameObjects are automatically added to the Hierarchy as soon as the first UI GameObject is added to a scene:

Rect Transforms for UI GameObjects represent a rectangular area rather than a single point, which is the case for scene GameObject Transforms. Rect Transforms describe how a UI element should be positioned and sized relative to its parent. Rect Transforms have a width and height that can be changed without affecting the local scale of the component. When the scale is changed for the Rect Transform of a UI element, this will also scale font sizes and borders on sliced images, and so on. If all four anchors are at the same point, resizing the Canvas will not stretch the Rect Transform. It will only affect its position. In this case, we'll see the Pos X and Pos Y properties, and the Width and Height of the rectangle. However, if the anchors are not all at the same point, Canvas resizing will result in stretching the element's rectangle. So instead of the Width, we'll see the values for Left and Right—the position of the horizontal sides of the rectangle to the sides of the Canvas, where the Width will depend on the actual Canvas width (and the same for Top/Bottom/Height).

Unity provides a set of preset values for pivots and anchors, making the most common values very quick and easy to assign to an element's Rect Transform. The following screenshot shows the 3 x 3 grid that allows you quick choices about the left, right, top, bottom, middle, horizontal, and vertical values. Also, the extra column on the right offers horizontal stretch presets, and the extra row at the bottom offers vertical stretch presets. Using the Shift+Alt keys sets the pivot and anchors when a preset is clicked:

The Unity manual provides a very good introduction to the Rect Transform. In addition, Ray Wenderlich's two-part Unity UI web tutorial also presents a helpful overview of the Rect Transform, pivots, and anchors. Both parts of Wenderlich's tutorial make great use of animated GIFs to illustrate the effect of different values for pivots and anchors:

There are three Canvas render modes:

  • Screen Space: Overlay: In this mode, the UI elements are displayed without any reference to any camera (there is no need for any Camera in the scene). The UI elements are presented in front of (overlaying) any sort of camera display of the scene contents.
  • Screen Space: Camera: In this mode, the Canvas is treated as a flat plane in the frustum (viewing space) of a Camera scene – where this plane is always facing the camera. So, any scene objects in front of this plane will be rendered in front of the UI elements on the Canvas. The Canvas is automatically resized if the screen size, resolution, or camera settings are changed.
  • World Space: In this mode, the Canvas acts as a flat plane in the frustum (viewing space) of a Camera scene – but the plane is not made to always face the Camera. How the Canvas appears is just as with any other objects in the scene, relative to where (if anywhere) in the camera's viewing frustum the Canvas plane is located and oriented.

In this chapter, we have focused on the Screen Space:Overlay mode. But all these recipes can be used with the other two modes as well.

Be creative! This chapter aims to act as a launching pad of ideas, techniques, and reusable C# scripts for your own projects. Get to know the range of Unity UI elements, and try to work smart. Often, a UI element exists with most of the components that you may need for something in your game, but you may need to adapt it somehow. An example of this can be seen in the recipe that makes a UI Slider non-interactive, instead using it to display a red-green progress bar for the status of a countdown timer. See this in the Displaying a countdown timer graphically with a UI Slider recipe.

Many of these recipes involve C# script classes that make use of the Unity scene-start event sequence of Awake() to all game objects, Start() to all GameObjects, then Update() every frame to every GameObject. Therefore, you'll see many recipes in this chapter (and the whole book) where we cache references to GameObject components in the Awake() method, and then make use of these components in Start() and other methods, once the scene is up and running.

Displaying a "Hello World" UI text message

The first traditional problem to be solved with a new computing technology is to display the Hello World message. In this recipe, you'll learn 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.
  3. In the Hierarchy panel, add a UI | Text GameObject to the scene—choose menu: GameObject | UI | Text. Name this GameObject Text-hello.
Using the Create menu : Alternatively, use the Create menu immediately below the Hierarchy tab, choosing menu: Create | UI | Text.
  1. Ensure that your new Text-hello GameObject is selected in the Hierarchy panel.
    Now, in
    the Inspector, 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 shows the Inspector panel with these settings:

  1. In the Rect Transform, click on the Anchor Presets square icon, which should result in several rows and columns of preset position squares appearing. Hold down Shift+Alt and click on the center one (middlerow and center column).
The screenshot of the Rect Transform in the Introduction highlights the middle-center preset needed for this recipe.
  1. Your Hello World text will now appear, centered nicely in the Game panel.

How it works...

You have added a new Text-hello GameObject to a scene. A parent Canvas and UI EventSystem will also have been automatically created.

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 some highlighting style to part of a string to be displayed to the user, the following are examples of some of the HTML-style markups that are available without the need to create separate UI Text objects:

  • 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 <color=green>green text </color>, but I am <color=#FF0000>red</color>
Learn more from the Unity online manual's Rich Text page at http://docs.unity3d.com/Manual/StyledText.html.

Displaying a digital clock

Whether it is the real-world time, or an in-game countdown clock, many games are enhanced by some form of clock or timer display. 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.

The following screenshot shows the kind of clock we will be creating in this recipe:

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 create a digital clock, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided Fonts folder.
  3. In the Hierarchy panel, add a UI | Text game object to the scene named Text-clock.
  4. Ensure that the Text-clock GameObject is selected in the Hierarchy panel. Now, in Inspector, ensure that the following properties are set:
    • Text set to read as time goes here (this placeholder text will be replaced by the time when the scene is running)
    • 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 the 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. Create a folder named _Scripts and create a C# script class called ClockDigital in this new folder:

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 
using System; 

public class ClockDigital : MonoBehaviour { 
  private Text textClock; 

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

  void Update (){ 
    DateTime time = DateTime.Now; 
    string hour = LeadingZero( time.Hour ); 
    string minute = LeadingZero( time.Minute ); 
    string second = LeadingZero( time.Second ); 

    textClock.text = hour + ":" + minute + ":" + 
second;
} string LeadingZero (int n){ return n.ToString().PadLeft(2, '0'); } }
Underscore prefix so items appear first in sequence

Since scripts and scenes are things that are most often accessed, prefixing their folder names with an underscore character, _as _Scenes and _Scripts, means they are always at the top in the Project panel.
Although the preceding code is useful for illustrating how to access the time component of a DateTime object individually, the Format(...) method of the String class can be used to format a DateTime object all in a single statement, for example, the preceding could be written more succinctly in a single statement:
String.Format("HH:mm:ss", DateTime.Now)
For more examples, see http://www.csharp-examples.net/string-format-datetime/.
  1. Ensure the Text-clock GameObject is selected in the Hierarchy panel.
  2. In the Inspector panel, add an instance of the ClockDigital script class as a component by clicking the Add Component button, selecting Scripts, and choosing the Clock Digital script class:
Add script components through drag and drop

Script components can also be added to GameObjects via drag and drop. For example, with the Text-clock GameObject selected in the Hierarchy panel, drag your ClockDigital script onto it to add an instance of this script class as a component to the Text-clock GameObject.
  1. When you run the scene, you will now see a digital clock that shows hours, minutes, and seconds at the top-center part of the screen.

How it works...

You added a Text GameObject to a scene. 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 have added the using statements for 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 in this way is referred to as caching—it means that code executed later does not need to repeat the computationally-expensive task of searching the GameObject hierarchy for a component of a particular type.

Note that an alternative approach would be to make textClock a public variable. This will allow us to assign it via drag and drop in the Inspector panel.

The Update() method is executed in every frame. The current time is stored in the time variable, and strings are created by adding leading zeros to the number values for the hours, minutes, and seconds properties of variable time.

This method finally updates the text property (that is, the letters and numbers that the user sees) to be a string, concatenating the hours, minutes, and seconds with colon
separator characters.

The LeadingZero(...) method takes as input an integer and returns a string of this number with leading zeros added to the left, if the value was less than 10.

There's more...

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

The Unity tutorial for animating an analog clock

Displaying a digital countdown timer

This recipe will show you how to display a digital countdown clock, as shown here:

Getting ready

This recipe adapts 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 in 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 panel, remove the scripted component, ClockDigital, from the Text-clock GameObject.
  3. In the Inspector panel, 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 = GetComponent<CountdownTimer>(); 
   } 
void Start() { countdownTimer.ResetTimer( 30 ); } void Update () { int timeRemaining = countdownTimer.GetSecondsRemaining(); string message = TimerMessage(timeRemaining); textClock.text = message; } private string TimerMessage(int secondsLeft) { if (secondsLeft <= 0){ return "countdown has finished"; } else { return "Countdown seconds remaining = " + secondsLeft; } } }
  1. When you run the Scene, you will now see a digital clock counting down from 30. When the countdown reaches zero, the message countdown has finished will be displayed.
Automatically add components with [RequireComponent(...)]

The DigitalCountdown script class requires the same GameObject to also have an instance of the CountdownTimer script class. Rather than having to manually attach an instance of a require script, you can use the [RequireComponent(...)] C# attribute immediately before the class declaration statement. This will result in Unity automatically attaching an instance of the required script class.

For example, by writing the following, Unity will add an instance of CountdownTimer as soon as an instance of the DigitalCountdown script class has been added as a component of a GameObject:

using UnityEngine;   
using UnityEngine.UI;   

[RequireComponent (typeof (CountdownTimer))]   
public class DigitalCountdown : MonoBehaviour {   
Learn more from the Unity documentation at https://docs.unity3d.com/ScriptReference/RequireComponent.html.

How it works...

You have 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 seconds remaining 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. This method finally updates the text property (that is, the letters and numbers that the user sees) of the textClock UI Text GameObject to equal to the string message about the remaining seconds.

The TimerMessage() method takes an integer as input, and if the value is zero or less, a message stating the timer has finished is returned. Otherwise (if greater than zero seconds remain) a message stating the number of remaining seconds is returned.

Creating a message that fades away

Sometimes, we want a message to display just for a certain time, and then fade away and disappear.

Getting ready

This recipe adapts the previous one. So, make a copy of the project for the 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 panel, remove the scripted component, DigitalCountdown, from the Text-clock GameObject.
  2. Create a C# script class, 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 will now see that the message on the screen slowly fades away, disappearing after five seconds.

How it works...

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 to start counting down from five 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 game object.

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 something, or we can multiply the maximum value by our decimal proportion, and we get the appropriate value. For example, if we wanted the number of degrees of a circle for a given 0.00.1 proportion, we just multiply by the maximum of 360, and so on.

The Update() method then retrieves the current color of the text being displayed (via textUI.color), updates its alpha property, and resets the text object to have this updated color value. The result is that each frame in the text object's transparency represents the current value of the proportion of the timer remaining until it fades to fully transparent when the timer gets to zero.

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 generally 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 a scrolling 3D text, simulating the famous opening credits of the movie Star Wars, which looks something like this:

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, in the 01_07 folder.

How to do it...

To display perspective 3D text, follow these steps:

  1. Create a new Unity 3D project (this ensures 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 panel.
  1. In the Hierarchy panel, select the Main Camera item, and, in the Inspector panel, set its properties as follows: Camera Clear Flags to solid color, Field of View to 150, and Background color to black.
  2. Import the provided Fonts and Text folders.
  3. In the Hierarchy panel, add a UI | Text game object to the scene—choose menu: GameObject | UI | Text. Name this GameObject as Text-star-wars.
  4. Set UI Text Text-star-wars 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 its Color to White. Use the anchor presets in Rect Transform to position this UI Text object at the top-center of the screen. Set Vertical Overflow to Overflow. Set Alignment Horizontal to center (leaving Alignment Vertical as top).
  5. In the Hierarchy panel, add a 3D Text game object to the scene choose menu: GameObject | 3D Object | 3D Text. Name this GameObject Text-crawler.
  6. In the Inspector panel, set the Transform properties for the Text-crawler GameObject as follows: Position (100, -250, 0), Rotation (15, 0, 0).
  7. In the Inspector panel, set the Text Mesh properties for the Text-crawler GameObject as follows:
    • Paste the content of the provided text file, star_wars.txt, into Text.
    • Set Offset Z = -20, Line Spacing = 1, and Anchor = Middle center
    • Set Font Size = 200, Font = SourceSansPro-BoldIt
  1. When the Scene is made to run, the Star Wars story text will now appear nicely squashed in 3D perspective on the screen.

How it works...

You have simulated the opening screen of Star Wars, with a flat UI Text object title at the top of the screen, and 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.

We have to make this text crawl like 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, ScrollZ, as a component to the Text-crawler GameObject:

using UnityEngine; using System.Collections; public class ScrollZ : MonoBehaviour { public float scrollSpeed = 20; void Update () { Vector3 pos = transform.position; Vector3 localVectorUp = transform.TransformDirection(0,1,0); 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, with a view to integrate 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. Therefore, you will need SDF fonts to work with this resource.

Getting ready

At the time of writing, TextMeshpro is a free Asset Store download and Unity Essentials Beta, so the first step is still to import it via the asset store. By the time you read this, you'll probably find TextMeshPro as a standard GameObject type that you can create in the Scene panel, with no downloading required. So, if required, open the Asset Store panel, search for TextMeshPro, and import this free asset package.

For this recipe, we have prepared the fonts that you need in a folder named Fonts & Materials in the 01_08 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 choose menu:
    GameObject | UI | TextMeshPro text. Name this GameObject Text-sophisticated.
TextMeshPro GameObjects do not have to be part of the UI Canvas. You can add a TextMeshPro GameObject to the Scene directly by choosing the Scene panel menu Create | 3D Object | TextMeshPro text.
  1. Ensure that your new Text-sophisticated GameObject is selected in the Hierarchy panel. In the Inspector for the 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 200
    • Alignment set to horizontal center
  3. Face:
    • Color set to white
    • Dilate set to 0
  4. Outline:
    • Color set to Red
    • Thickness set to 0.1
  5. Underlay (shadow):
    • Offset X set to 1
    • Offset Y set to -1
    • Dilate set to 1

The following screenshot shows the Inspector panel with these settings:

  1. The Text-sophisticated GameObject will now appear as very large, with a white inner, red outline, and a drop shadow to the lower right.

How it works...

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

There are hundreds of settings for a TextMeshPro component, and therefore 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 to substrings. The following code illustrates some, including the following:

<sprite=5> inline sprite graphics 

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

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

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

Learn more from 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:

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 panel to a 400 x 300 size. Do this by first displaying the Game panel, and then creating a new Resolution in the drop-down menu at the top of the panel. Click the plus symbol at the bottom of this menu, setting Label = Chapter 2, Width = 400, and Height = 300. Click OK and the Game panel should be set to this new resolution:
Alternatively, you can set the default Game panel resolution through menu Edit | Project Settings | Player and then the Resolution and Presentation width and height in the Inspector (having turned off the Full Screen option).
  1. Import the provided Images folder. In the Inspector tab, ensure that the unity_logo image has the Texture Type set to Default. If it has some other type, then choose Default from the drop-down list, and click on the Apply button.
  2. In the Hierarchy panel, add a UI | RawImage GameObject named RawImage-logo to the scene.
  1. Ensure that the RawImage-logo GameObject is selected in the Hierarchy panel. In the Inspector for the RawImage (Script) component, click the file viewer circle icon at the right side of the Texture property, and select image unity_logo, as shown in the following screenshot:
An alternative way of assigning this Texture is to drag the unity_logo image from your Project folder (Images) into the Raw Image (Script) public property Texture.
  1. Click on the Set Native Size button to resize the image so it is no longer stretched and distorted.
  2. In Rect Transform, click on the Anchor Presets square icon, which will result in several rows and columns of preset position squares appearing. Hold down Shift + Alt and click on the top row and the center column.
  3. The image will now be positioned neatly at the top of the Game panel, and will be horizontally centered.

How it works...

You have ensured that an image has the Texture Type set to Default. You added a UI RawImage control to the scene. The RawImage control has been made to display the unity_logo image file.
The image has been positioned at the top-center of the Game panel.

There's more...

There 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 on 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 the distortion and stretching of a UI Sprite GameObject, then in the Inspector panel, 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.

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.

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

How to do it...

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

  1. Create a new Unity 2D project.
  2. Open the Asset Store panel, search for Fungus, and Import this free asset package (search for Fungus and free).
  3. Create a new Fungus Flowchart GameObject by choosing menu: Tools | Fungus | Create | Flowchart.
  4. Display and dock the Fungus Flowchart window panel by choosing menu: Tools | Fungus | Flowchart Window.
  5. There will be one block in the Flowchart Window. Click on this block to select it (a green border appears around the block to indicate that it is selected). In the Inspector panel, change the Block Name of this block to Start:
  1. Each Block in a Flowchart follows a sequence of commands. So in the Inspector, we are now going to create a sequence of (Say) commands to display two sentences to the user when the game runs.
  2. Ensure that the Start block is still selected in the Flowchart panel. Click on the plus (+) button at the bottom section of the Inspector panel to display the menu of Commands, and select the Narrative | Say command:
  1. Since we only have one command for this block, that command will automatically be selected (highlighted green) in the top part of the Inspector. The bottom half of the Inspector presents the properties for the currently-selected Command, as shown in the following screenshot. In the bottom half of the Inspector, for the Story Text property, enter the text of the question that you wish to be presented to the user, which is How are you today?:
  1. Create another Say Command, and type the following for its Story Text property: Very well thank you.
  2. When you run the game, the user will first be presented with the How are you today? text (hearing a clicking noise as each letter is typed on screen). After the user clicks on the continue triangle button (at the bottom-right part of the dialog window), they will be presented with the second sentence: Very well thank you.

How it works...

You have created a new Unity project, and imported the Fungus asset package, which contains the Fungus Unity menus, windows, and commands, and also the example projects.

You have added a Fungus Flowchart to your scene with a single Block that you have 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 continue button. Fungus offers many more features, including menus, animations, and control of sounds and music, the details of which can be found in the next recipe, and by exploring their provided example projects, and their websites:

Creating a Fungus character dialog with images

The Fungus dialog system 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:

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 panel, and Import the Fungus dialogue asset package (this includes the Fungus Examples, whose images we’ll use for the two characters).
  3. Create a new Fungus Flowchart GameObject by choosing menu: Tools | Fungus | Create | Flowchart.
  4. Display and dock the Fungus Flowchart window panel by choosing menu: Tools | Fungus | Flowchart Window.
  5. Change the name of the only Block in the Flowchart to The case of the missing violin.
  6. Create a new Character by choosing menu: Tools | Fungus | Create | Character.
  7. You should now see a new Character GameObject in the Hierarchy.
  8. With GameObject Character 1 – Sherlock selected in the Project panel, edit its properties in the Inspector:
    • Rename this GameObject Character 1 – Sherlock.
    • In its Character(Script) component, set the Name Text to Sherlock and the Name Color to green.
    • In the Inspector, click the Add Portrait button (the plus sign "+"), to get a "slot" into which to add a portrait image.
    • Drag the appropriate image into your new portrait image slot (in this screenshot, we used the "confident" image from the Sherlock example project: Fungus Examples | Sherlock | Portraits | Sherlock):
  1. Repeat steps 6-8 above to create a second character, John, using Name Color = blue, and Portrait Image = annoyed.
  2. Select your Block in the Fungus Flowchart, so you can add some Commands to be executed.
  3. Create a Say command, for Character 1 - Sherlock, saying Watson, have you seen my violin? and choose the confident portrait (since this is the only one we added to the character):
  1. Add a second Say command, this time for Character 2 John, saying No, why don't you find it yourself using your amazing powers of deduction.. and choose the annoyed portrait:
  1. Run the scene you should see a sequence of statements, clearly showing who is saying both with (colored) name text AND the portrait image you selected for each Say command (after Sherlock’s text has finished appearing, click the box to start John’s sentence).

How it works...

You have created a new Unity project with the Fungus asset package.

You have 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 to Say commands, stating which character was saying each sentence, and which portrait to use (if you had added more portrait images, you could select different images to indicate the emotion of the character speaking).

There's more...

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

Data-driven conversations

Fungus offers a data-driven approach to conversations. The character and portrait (and facing direction, and movement onto-off the stage, and so on) can be defined through text in a simple format, 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...

Learn more about the Fungus conversation system on their documentation pages: http://fungusdocs.snozbot.com/conversation_system.html.

Left arrow icon Right arrow icon

Key benefits

  • Become proficient at traditional 2D and 3D game development
  • Build amazing interactive interfaces with Unity's UI system
  • Develop professional games with realistic animation and graphics, materials and cameras, and AI with Unity 2018

Description

With the help of the Unity 2018 Cookbook, you’ll discover how to make the most of the UI system and understand how to animate both 2D and 3D characters and game scene objects using Unity's Mecanim animation toolsets. Once you’ve got to grips with the basics, you will familiarize yourself with shaders and Shader Graphs, followed by understanding the animation features to enhance your skills in building fantastic games. In addition to this, you will discover AI and navigation techniques for nonplayer character control and later explore Unity 2018’s newly added features to improve your 2D and 3D game development skills. This book provides many Unity C# gameplay scripting techniques. By the end of this book, you'll have gained comprehensive knowledge in game development with Unity 2018.

Who is this book for?

Unity 2018 Cookbook is for you if you want to explore a wide range of Unity scripting and multimedia features and find ready-to-use solutions for many game features. This book also helps programmers explore multimedia features. It is assumed that you already know basics of Unity and have some programming knowledge of C#.

What you will learn

  • Get creative with Unity's shaders and learn to build your own shaders with the new Shader Graph tool
  • Create a text and image character dialog with the free Fungus Unity plugin
  • Explore new features integrated into Unity 2018, including TextMesh Pro and ProBuilder
  • Master Unity audio, including ducking, reverbing, and matching pitch to animation speeds
  • Work with the new Cinemachine and timeline to intelligently control camera movements
  • Improve ambiance through the use of lights and effects, including reflection and light probes
  • Create stylish user interfaces with the UI system, including power bars and clock displays

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2018
Length: 794 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788471909
Vendor :
Unity Technologies
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 31, 2018
Length: 794 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788471909
Vendor :
Unity Technologies
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 119.97
Unity 2018 Artificial Intelligence Cookbook
€36.99
Unity 2018 By Example
€36.99
Unity 2018 Cookbook
€45.99
Total 119.97 Stars icon
Banner background image

Table of Contents

21 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 UIs Chevron down icon Chevron up icon
Playing and Manipulating Sounds Chevron down icon Chevron up icon
Creating Textures, Maps, and Materials Chevron down icon Chevron up icon
Shader Graphs and Video Players Chevron down icon Chevron up icon
Using Cameras Chevron down icon Chevron up icon
Lights and Effects Chevron down icon Chevron up icon
2D Animation Chevron down icon Chevron up icon
3D Animation Chevron down icon Chevron up icon
Webserver 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
Design Patterns Chevron down icon Chevron up icon
Editor Extensions and Immediate Mode GUI (IMGUI) Chevron down icon Chevron up icon
Working with External Resource Files and Devices Chevron down icon Chevron up icon
Working with Plain Text, XML, and JSON Text Files Chevron down icon Chevron up icon
Virtual Reality and Extra Features Chevron down icon Chevron up icon
Automated Testing Chevron down icon Chevron up icon
Bonus Chapters Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(3 Ratings)
5 star 66.7%
4 star 0%
3 star 0%
2 star 0%
1 star 33.3%
Hanseung Chae Nov 12, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a great book that if you are just starting Unity. Also, it has some contents valid to the old user who had never touched Unity after 5 released. There is a good solution how to handle UI stuffs and optimizing.
Amazon Verified review Amazon
Amazon Customer Oct 31, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Delivered on time, perfect
Amazon Verified review Amazon
Maury Amezcua Jan 08, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Nothing against the authors of the books but the Publisher Packt. All these "books" with this cover format are actually written specifically for a online learning database, so the pictures in the book are really small and the project files mentioned in the text aren't included with the Amazon purchase. It's like the publisher just went through each lesson and converted the pages to PDF, then turned them into books to sell on Amazon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.