Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Unity 2018 Cookbook - Third Edition
Unity 2018 Cookbook - Third Edition

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

By Matt Smith , Francisco Queiroz
$47.99 $32.99
Book Aug 2018 794 pages 3rd Edition
eBook
$47.99 $32.99
Print
$60.99
Subscription
$15.99 Monthly
eBook
$47.99 $32.99
Print
$60.99
Subscription
$15.99 Monthly

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
Buy Now

Product Details


Publication date : Aug 31, 2018
Length 794 pages
Edition : 3rd Edition
Language : English
ISBN-13 : 9781788471909
Vendor :
Unity Technologies
Category :
Table of content icon View table of contents Preview book icon Preview Book

Unity 2018 Cookbook - Third Edition

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.

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

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
Buy Now

Product Details


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

Table of Contents

22 Chapters
Preface Chevron down icon Chevron up icon
1. Displaying Data with Core UI Elements Chevron down icon Chevron up icon
2. Responding to User Events for Interactive UIs Chevron down icon Chevron up icon
3. Inventory UIs Chevron down icon Chevron up icon
4. Playing and Manipulating Sounds Chevron down icon Chevron up icon
5. Creating Textures, Maps, and Materials Chevron down icon Chevron up icon
6. Shader Graphs and Video Players Chevron down icon Chevron up icon
7. Using Cameras Chevron down icon Chevron up icon
8. Lights and Effects Chevron down icon Chevron up icon
9. 2D Animation Chevron down icon Chevron up icon
10. 3D Animation Chevron down icon Chevron up icon
11. Webserver Communication and Online Version-Control Chevron down icon Chevron up icon
12. Controlling and Choosing Positions Chevron down icon Chevron up icon
13. Navigation Meshes and Agents Chevron down icon Chevron up icon
14. Design Patterns Chevron down icon Chevron up icon
15. Editor Extensions and Immediate Mode GUI (IMGUI) Chevron down icon Chevron up icon
16. Working with External Resource Files and Devices Chevron down icon Chevron up icon
17. Working with Plain Text, XML, and JSON Text Files Chevron down icon Chevron up icon
18. Virtual Reality and Extra Features Chevron down icon Chevron up icon
19. Automated Testing Chevron down icon Chevron up icon
20. Bonus Chapters Chevron down icon Chevron up icon
21. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

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

Filter reviews by


No reviews found
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.