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

Unity 5.x Cookbook: More than 100 solutions to build amazing 2D and 3D games with Unity

eBook
$9.99 $47.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

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

Unity 5.x Cookbook

Chapter 1. Core UI – Messages, Menus, Scores, and Timers

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 message
  • Displaying an image
  • Creating UI Buttons to move between scenes
  • Organizing images inside panels and changing panel depths via buttons
  • Displaying the value of an interactive UI Slider
  • Displaying a countdown timer graphically with a UI Slider
  • Displaying a radar to indicate the relative locations of objects
  • Creating UIs with the Fungus open-source dialog system
  • Setting custom mouse cursor images
  • Input Fields component for text entry
  • Toggles and radio buttons via Toggle Groups

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, text boxes, and so on), 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 wide range of the Unity 5 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 5 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, and so on. 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 childed 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.
  • Panel: UI objects can be grouped together (logically and physically) with UI Panels. Panels can play several roles, including providing a GameObject parent in the Hierarchy for a related group of controls. They can provide a visual background image to graphically relate controls on the screen, and they can also have scripted resize and drag interactions added, if desired.
  • Visual UI controls: The visible UI controls themselves include Button, Image, Text, Toggle, and so on.
  • Interaction UI controls: These are non-visible components that are added to GameObjects; examples include Input Field and Toggle Group.
  • 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. Read more about these core features below.
  • Sibling Depth: The bottom-to-top display order (what appears on the top of what) for a UI element is determined initially by their sequence in the Hierarchy. At designtime, this can be manually set by dragging GameObjects into the desired sequence in the Hierarchy. At runtime, we can send messages to the Rect Transforms of GameObjects to dynamically change their Hierarchy position (and therefore, the display order), as the game or user interaction demands. This is illustrated in the Organizing images inside panels and changing panel depths via buttons recipe in this chapter.

The following diagram shows how there are 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 descendent 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.

The big picture

UI Rect Transforms represents 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 relatively 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, then this will also scale font sizes and borders on sliced images, and so on. If all four anchors are at the same point, then 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, then Canvas resizing will result in a stretching of 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 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 and ALT keys sets the pivot and anchors when a preset is clicked.

The big picture

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 great 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 equally 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.

Displaying a "Hello World" UI text message

The first traditional problem to be solved with a new computing technology is often 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, and in the center of the screen.

Displaying a "Hello World" UI text message

Getting ready

For this recipe, we have prepared the font that you need in a folder named Fonts in the 1362_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.

    Note

    Alternatively, use the Create menu immediately below the Hierarchy tab, choosing menu: Create | UI | Text.

  4. 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:

    How to do it...
  5. Now, 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 and ALT and click on the center one (row middle and column center).
    How to do it...
  6. 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 use 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 that 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 a 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>

    Note

    Learn more from the Unity online manual Rich Text page at: http://docs.unity3d.com/Manual/StyledText.html.

Displaying a digital clock

Whether it is the real-world time, or perhaps 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:

Displaying a digital clock

Getting ready

For this recipe, we have prepared the font that you need in a folder named Fonts in the 1362_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 GameObject Text-clock 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
  5. Now, 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 and ALT and click on the top and column center rows.
  6. 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 Start (){
        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');
      }
    }
  7. With GameObject Text-clock selected in the Hierarchy panel, drag your ClockDigital script onto it to add an instance of this script class as a component to GameObject Text-clock, as shown in the following screenshot:
    How to do it...
  8. When you run the scene, you will now see a digital clock, showing hours, minutes, and seconds, at the top-center part of the screen.

How it works...

You added a Text GameObject to a scene. You have 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 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 Start() 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.

Note

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 that you don't want to miss.

The Unity tutorial for animating an analogue clock

Unity has published a nice tutorial on how to create 3D objects, and animate them through C# script to display an analogue clock at https://unity3d.com/learn/tutorials/modules/beginner/scripting/simple-clock.

Displaying a digital countdown timer

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

Displaying a digital countdown timer

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 1362_01_03 folder.

How to do it...

To create a digital countdown timer, follow these steps:

  1. In the Inspector panel, remove the scripted component, ClockDigital, from GameObject Text-clock.
  2. Create a DigitalCountdown C# script class containing the following code, and add an instance as a scripted component to GameObject Text-clock:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using System;
    
    public class DigitalCountdown : MonoBehaviour {
      private Text textClock;
    
      private float countdownTimerDuration;
      private float countdownTimerStartTime;
    
      void Start (){
        textClock = GetComponent<Text>();
        CountdownTimerReset(30);
      }
    
      void Update (){
        // default - timer finished
        string timerMessage = "countdown has finished";
        int timeLeft = (int)CountdownTimerSecondsRemaining();
    
        if(timeLeft > 0)
          timerMessage = "Countdown seconds remaining = " + LeadingZero( timeLeft );
    
        textClock.text = timerMessage;
      }
    
      private void CountdownTimerReset (float delayInSeconds){
        countdownTimerDuration = delayInSeconds;
        countdownTimerStartTime = Time.time;
      }
    
      private float CountdownTimerSecondsRemaining (){
        float elapsedSeconds = Time.time - countdownTimerStartTime;
        float timeLeft = countdownTimerDuration - elapsedSeconds;
        return timeLeft;
      }
    
      private string LeadingZero (int n){
        return n.ToString().PadLeft(2, '0');
      }
    }
  3. 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.

How it works...

You added a Text GameObject to a scene. You have added an instance of the DigitalCountdown C# script class to that GameObject.

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 a time remaining message (or a timer complete message). Then, a call is made to the CountdownTimerReset(…) method, passing an initial value of 30 seconds.

The Start() method (executed when the scene begins) sets the textClock variable to find the Text component in the GameObject where our scripted object has been added.

The Update() method is executed in every frame. This method initially sets the timerMessage variable to a message, stating that the timer has finished (the default message to display). Then the seconds remaining are tested to be greater than zero. And if so, then the message variable has its contents changed to display the integer (whole) number of the seconds remaining in the countdown—retrieved from the CountdownTimerSecondsRemaining() method. This method finally updates the text property (that is, the letters and numbers that the user sees) to be a string with a message about the remaining seconds.

The CountdownTimerReset(…) method records the number of seconds provided, and the time the method was called.

The CountdownTimerSecondsRemaining() method returns an integer value of the number of seconds remaining.

Creating a message that fades away

Sometimes, we want a message to display just for a certain time, and then fade away and disappear, which will appear as shown in this screenshot:

Creating a message that fades away

Getting ready

This recipe adapts the first recipe in this chapter, so make a copy of that project to work on for this recipe.

For this recipe, we have prepared the script that you need in a folder named Scripts in the 1362_01_04 folder.

How to do it...

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

  1. Import the provided C# script class called CountdownTimer.
  2. Ensure that GameObject Text-hello is selected in the Hierarchy tab. Then, attach an instance of the CountdownTimer C# script class as a component of this GameObject.
  3. Create a C# script class, FadeAway, containing the following code, and add an instance as a scripted component to the GameObject Text-hello:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class FadeAway : MonoBehaviour {
      private CountdownTimer countdownTimer;
      private Text textUI;
      private int fadeDuration = 5;
      private bool fading = false;
    
      void Start (){
        textUI = GetComponent<Text>();
        countdownTimer = GetComponent<CountdownTimer>();
    
        StartFading(fadeDuration);
      }
    
      void Update () {
        if(fading){
          float alphaRemaining = countdownTimer.GetProportionTimeRemaining();
          print (alphaRemaining);
          Color c = textUI.material.color;
          c.a = alphaRemaining;
          textUI.material.color = c;
    
          // stop fading when very small number
          if(alphaRemaining < 0.01)
            fading = false;
        }
      }
    
      public void StartFading (int timerTotal){
        countdownTimer.ResetTimer(timerTotal);
        fading = true;
      }
    }
  4. When you run the scene, you will now see that the message on the screen slowly fades away, disappearing after 5 seconds.

How it works...

An instance of the provided CountdownTimer script class was added as a component to the GameObject Text-hello.

You added to the GameObject Text-hello an instance of the scripted class, FadeAway. The Start()method caches references to the Text and CountdownTimer components in the countdownTimer and textUI variables. Then, it calls the StartFading(…)method, passing in the number 5, so that the message will have faded to invisible after 5 seconds.

The StartFading(…) method starts this timer scripted component to countdown to the given number of seconds. It also sets the fading Boolean flag variable to true.

The Update() method, in each frame, tests if the fading variable is true. If it is true, then the alpha (transparency) component of the color of the Text-hello object is set to a value between 0.0 and 1.0, based on the proportion of the time remaining in the CountdownTimer object. Finally, if the proportion of time remaining is less than a very small value (0.01), then the fading variable is set to false (to save the processing work since the text is now invisible).

Displaying a perspective 3D text message

Unity provides an alternative way to display text in 3D via the TextMesh 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 instructions scenes, and the like.

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:

Displaying a perspective 3D text message

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 1362_01_04 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 that we want to create).

    Note

    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.

  2. 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. Also set the Background color to black.
  3. Import the provided Fonts folder.
  4. 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. Set its Text Content as Star Wars (with each word on a new line). Then, set its Font to Xolonium Bold, and its Font Size to 50. Use the anchor presets in Rect Transform to position this UI Text object at the top center of the screen.
  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 GameObject Text-crawler as follows: Position (0, -300, -20), Rotation (15, 0, 0).
  7. In the Inspector panel, set the Text Mesh properties for GameObject Text-crawler as follows:
    • Paste the content of the provided text file, star_wars.txt, into Text.
    • Set Offset Z = 20, Line Spacing = 0.8, and Anchor = Middle center
    • Set Font Size = 200, Font = SourceSansPro-BoldIt
  8. 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 the movie 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 that 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 GameObject Text-crawler:

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

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

Note

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

Displaying an image

There are many cases where we wish to display an image onscreen, including logos, maps, icons, splash graphics, and so on. In this recipe, we will display an image at the top of the screen, and make it stretch to fit whatever width that the screen is resized to.

The following screenshot shows Unity displaying an image:

Displaying an image

Getting ready

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

How to do it...

To display a stretched image, follow these steps:

  1. Create a new Unity 3D project.

    Note

    3D projects will, by default, import images as a Texture, and 2D projects will import images as Sprite (2D and UI). Since we're going to use a RawImage UI component, we need our images to be imported as textures.

  2. Set the Game panel to a 400 x 300 size. Do this via menu: Edit | Project Settings | Player. Ensure that the Resolution | Default is Full Screen setting check is unchecked, and the width/height is set to 400 x 300. Then, in the Game panel, select Stand Alone (400 x 300). This will allow us to test the stretching of our image to a width of 400 pixels.
  3. Import the provided folder, which is called Images. In the Inspector tab, ensure that the unity5_learn image has Texture Type set to Texture. If it does not, then choose Texture from the drop-down list, and click on the Apply button. The following screenshot shows the Inspector tab with the Texture settings:
    How to do it...
  4. In the Hierarchy panel, add a UI | RawImage GameObject to the scene named RawImage-unity5.

    Note

    If you wish to prevent the distortion and stretching of an image, then use the UI Sprite GameObject instead, and ensure that you check the Preserve Aspect option, in its Image (Script) component, in the Inspector panel.

  5. Ensure that the GameObject RawImage-unity5 is selected in the Hierarchy panel. From your Project folder (Images), drag the unity5_learn image into the Raw Image (Script) public property Texture. Click on the Set Native Size button to preview the image before it gets stretched, as shown:
    How to do it...
  6. Now, 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 and ALT and click on the top row and the stretch column.
  7. The image will now be positioned neatly at the top of the Game panel, and will be stretched to the full width of 400 pixels.

How it works...

You have ensured that an image has Texture Type set to Texture. You added a UI RawImage control to the scene. The RawImage control has been made to display the unity5_learn image file.

The image has been positioned at the top of the Game panel, and using the anchor and pivot presets, it has made the image stretch to fill the whole width, which we set to 400 pixels via the Player settings.

There's more...

There are some details that you don't want to miss:

Working with 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), then the UI Sprite 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, options to preserve aspect ratio, and so on.

Working with Sprites and UI Image components

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 2, Inventory GUIs.

Creating UI Buttons to move between scenes

As well as scenes where the player plays the game, most games will have menu screens, which display to the user messages about instructions, high scores, the level they have reached so far, and so on. Unity provides the UI Buttons to make it easy to offer users a simple way to indicate their choice of action on such screens.

In this recipe, we'll create a very simple game consisting of two screens, each with a button to load the other one, similar to the following screenshot:

Creating UI Buttons to move between scenes

How to do it...

To create a button-navigable multi-scene game, follow these steps:

  1. Create a new Unity 2D project.
  2. Save the current (empty) scene, naming it page1.
  3. Add a UI Text object positioned at the top center of the scene, containing text Main Menu / (page 1) in a large font size.
  4. Add a UI Button to the scene positioned in the middle center of the screen. In the Hierarchy panel, click on the show children triangle to display the UI Text child of this button GameObject. Select the Text button-child GameObject, and in the Inspector panel for the Text property of the Text (Script) component, enter the button text called goto page 2, as shown here:
    How to do it...
  5. Add the current scene to the build, choosing menu: File | Build Settings…. Then, click on the Add Current button so that the page1 scene becomes the first scene on the list of Scenes in the Build.

    Note

    We cannot tell Unity to load a scene that has not been added to the list of scenes in the build. We use the Application.LoadLevel(…)code to tell Unity to load the scene name (or numeric index) that is provided.

  6. Create a C# script class, MenuActions, containing the following code, and add an instance as a scripted component to the Main Camera:
    using UnityEngine;
    using System.Collections;
    
    public class MenuActions : MonoBehaviour {
      public void MENU_ACTION_GotoPage(string sceneName){
        Application.LoadLevel(sceneName);
      }
    }
  7. Ensure that the Button is selected in the Hierarchy and click on the plus sign "+" button at the bottom of the Button (Script) component, in the Inspector view, to create a new OnClick event handler for this button.
  8. Drag the Main Camera from the Hierarchy over the Object slot—immediately below the menu saying Runtime Only. This means that when the Button receives an OnClick event, we can call a public method from a scripted object inside the Main Camera.
  9. Now, select the MENU_ACTION_GotoPage() method from the MenuActions drop-down list (initially showing No Function). Type page2 (the name of the scene we want to be loaded when this button is clicked) in the text box, below the method's drop-down menu. This page2 string will be passed to the method when the button receives an OnClick event message, as shown here:
    How to do it...
  10. Save the current scene, create a new empty scene, and then save this new scene as page2.
  11. Follow the similar steps for this scene. Add a UI Text GameObject, displaying the text Instructions / (page 2) in a large font size. Add a UI Button, showing the goto page 1 text.
  12. Add the current scene to the build (so now, both page1 and page2 will be listed in the build).
  13. Add an instance of MenuActions script class to the Main Camera.
  14. Select the Button in the Hierarchy panel, and add an On Click event handler, which will pass the MENU_ACTION_GotoPage() method the string page1 (the name of the scene we want to be loaded when this button is clicked).
  15. Save the scene.
  16. When you run the page1 scene, you will be presented with your Main Menu text and a button, which when clicked, makes the game load the page2 scene. On scene page2, you'll have a button to take you back to page1.

How it works...

You have created two scenes, and added both of them to the game build. Each scene has a button, which when clicked (when the game is playing), makes Unity load the (named) other scene. This is made possible because when each button is clicked, it runs the MENU_ACTION_GotoPage(…)method from the scripted MenuActions component inside the Main Camera. This method inputs a text string of the name of the scene to be loaded, so that the button in the page1 scene gives the string name of page2 as the scene to be loaded, and vice versa.

When a UI Button is added to the Hierarchy panel, a child UI Text object is also automatically created, and the content of the Text property of this UI Text child is the text that the user sees on the button.

There's more...

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

Visual animation for the button mouse-over

There are several ways in which we can visually inform the user that the button is interactive when they move their mouse cursor over it. The simplest is to add a color tint that will appear when the mouse is over the button—this is the default Transition. With the Button selected in the Hierarchy, choose a tint color (for example, red), for the Highlighted Color property of the Button (Script) component, in the Inspector tab, as shown here:

Visual animation for the button mouse-over

Another form of visual Transition to inform the user of an active button is Sprite Swap. In this case, properties for different images for Targeted/Highlighted/Pressed/Disabled are available in the Inspector tab. The default Targeted Graphic is the built-in Unity Button (image) – this is the grey rounded rectangle default when GameObjects buttons are created. Dragging in a very different-looking image for the Highlighted Sprite is an effective alternative to set a color hint. We have provided a rainbow.png image with the project for this recipe that can be used for the Button mouse over Highlighted Sprite. The following screenshot shows the button with this rainbow background image:

Visual animation for the button mouse-over

Animating button properties on mouse over

Finally, animations can be created for dynamically highlighting a button to the user, for example, a button might get larger when the mouse is over it, and then it might shrink back to its original size when the mouse pointer is moved away. These effects are achieved by choosing the Animation option for the Transition property, and by creating an animation controller with triggers for the Normal, Highlighted, Pressed and Disabled states. To animate a button for enlargement when the mouse is over it (the highlighted state), do the following:

  1. Create a new Unity 2D project.
  2. Create a button.
  3. In the Inspector Button (Script) component, set the Transition property to Animation.
  4. Click the Auto Generate Animation button (just below the Disabled Trigger property) for the Button (Script) component, as shown here:
    Animating button properties on mouse over
  5. Save the new controller by naming it button-animation-controller.
  6. Ensure that the Button GameObject is selected in the Hierarchy. Then, in the Animation panel, select the Highlighted clip from the drop-down menu, as shown here:
    Animating button properties on mouse over
  7. In the Animation panel, click on the red record circle button, and then click on the Add Property button, choosing to record changes to the Rect Transform | Scale property.
  8. Two key frames will have been created, delete the second one at 1:00 (since we don't want a "bouncing" button), as shown in the following screenshot .
    Animating button properties on mouse over
  9. Select the first key frame at 0:00 (the only one now!). Then, in the Inspector view, set the X and Y scale properties of the Rect Transform component to (1.2, 1.2).
  10. Finally, click on the red record circle button for the second time to end the recording of the animation changes.
  11. Save and run your scene, and you will see that the button smoothly animates to get larger when the mouse is over it, and then smoothly returns to its original size when the mouse is moved away.

The following web pages offer video and web-based tutorials on UI animations:

Organizing images inside panels and changing panel depths via buttons

UI Panels are provided by Unity to allow UI controls to be grouped and moved together, and also to visually group elements with an Image background (if desired). The sibling depth is what determines which UI elements will appear above or below others. We can see the sibling depth explicitly in the Hierarchy, since the top-to-bottom sequence of UI GameObjects in the Hierarchy sets the sibling depth. So, the first item has a depth of 1, the second has a depth of 2, and so on. The UI GameObjects with larger sibling depths (further down the Hierarchy) appear above the UI GameObjects with lower sibling depths.

In this recipe, we'll create three UI panels, each showing a different playing card image. We'll also add four triangle arrangement buttons to change the display order (move to bottom, move to top, move up one, and move down one).

Organizing images inside panels and changing panel depths via buttons

Getting ready

For this recipe, we have prepared the images that you need in a folder named Images in the 1362_01_08 folder.

How to do it...

To create the UI Panels whose layering can be changed by the user-clicking buttons, follow these steps:

  1. Create a new Unity 2D project.
  2. Create a new UI Panel named Panel-jack-diamonds. Position it in the middle-center part of the screen, and size it 200 pixels wide by 300 pixels high. Uncheck the Image (Script) component for this panel (since we don't want to see the default semi-transparent rectangular grey background image of a panel).
  3. Create a new UI Image, and child this image to Panel-jack-diamonds.
  4. Position the Panel-jack-diamonds image at center-middle, and size it to 200 x 300. Drag the Jack-of-diamonds playing card image into the Source Image property, for the Image (Script) component in the Inspector tab.
  5. Create a UI Button named Button-move-to-front. Child this button to Panel-jack-diamonds. Delete the Text child GameObject of this button (since we'll use an icon to indicate what this button does).
  6. Size the Button-move-to-front button to 16 x 16, and position it top-center of the player card image, so that it can be seen at the top of the playing card. Drag the icon_move_to_front arrangement triangle icon image into the Source Image property, for the Image (Script) component, in the Inspector view.
  7. Ensure that the Button-move-to-front button is selected in the Hierarchy. Then, click on the plus sign (+) at the bottom of the Button (Script) component, in the Inspector view to create a new OnClick event handler for this button.
  8. Drag Panel-jack-diamonds from the Hierarchy over the Object slot (immediately below the menu saying Runtime Only).
  9. Now, select the RectTransform.SetAsLastSibling method from the drop-down function list (initially showing No Function).

    Note

    This means that when the Button receives an OnClick event, the RectTransform of the Panel will be sent the SetAsLastSibling message – this will move the Panel to the bottom of the GameObjects in the Canvas, and therefore will move this Panel in front of all other GameObjects in the Canvas.

    How to do it...
  10. Repeat step 2; create a second Panel with a move-to-front button. Name this second Panel Panel-2-diamonds, then move and position it slightly to the right of Panel-jack-diamonds, allowing both the move-to-front buttons to be seen.
  11. Save your scene and run the game. You will be able to click the move-to-front button on either of the cards to move that card's panel to the front. If you run the game with the Game panel not maximized, you'll actually see the panels changing order in the list of the children of the Canvas in the Hierarchy.

How it works...

You've created two UI Panels, each panel containing an image of a playing card and a button whose action will make its parent panel move to the front. The button's action illustrates how the OnClick function does not have to be the calling of a public method of a scripted component of an object, but it can be sending a message to one of the components of the targeted GameObject—in this instance we send the SetAsLastSibling message to the RectTransform of the Panel in which the Button is located.

There's more...

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

Moving up or down by just one position, using scripted methods

While the Rect Transform offers a useful SetAsLastSibling (move to front) and SetAsFirstSibling (move to back), and even SetSiblingIndex (if we knew exactly what position in the sequence to type in), there isn't a built-in way to make an element move up or down, just a single position in the sequence of GameObjects in the Hierarchy panel. However, we can write two straightforward methods in C# to do this, and we can add buttons to call these methods, providing full control of the top-to-bottom arrangement of the UI controls on the screen. To implement four buttons (move-to-front/move-to-back/up one/down one), do the following:

  1. Create a C# script class called ArrangeActions, containing the following code, and add an instance as a scripted component to each of your Panels:
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.EventSystems;
    using System.Collections;
    
    public class ArrangeActions : MonoBehaviour {
      private RectTransform panelRectTransform;
    
      void Start(){
        panelRectTransform = GetComponent<RectTransform>();
      }
    
      public void MoveDownOne(){
        print ("(before change) " + GameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
    
        int currentSiblingIndex = panelRectTransform.GetSiblingIndex();
        panelRectTransform.SetSiblingIndex( currentSiblingIndex - 1 );
    
        print ("(after change) " + GameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
      }
    
      public void MoveUpOne(){
        print ("(before change) " + GameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
    
        int currentSiblingIndex = panelRectTransform.GetSiblingIndex();
        panelRectTransform.SetSiblingIndex( currentSiblingIndex + 1 );
    
        print ("(after change) " + GameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
      }
    }
  2. Add a second button to each card panel, this time, using the arrangement triangle icon image called icon_move_to_front, and set the OnClick event function for these buttons to SetAsFirstSibling.
  3. Add two further buttons to each card panel with the up and down triangle icon images: icon_down_one and icon_up_one. Set the OnClick event handler function for the down-one buttons to call the MoveDownOne() method, and set the functions for the up-one buttons to call the MoveUpOne() method.
  4. Copy one of the panels to create a third card (this time showing the Ace of diamonds). Arrange the three cards so that you can see all four buttons for at least two of the cards, even when those cards are at the bottom (see the screenshot at the beginning of this recipe).
  5. Save the scene and run your game. You will now have full control over the layering of the three card panels.

Displaying the value of an interactive UI Slider

This recipe illustrates how to create an interactive UI Slider, and execute a C# method each time the user changes the Slider value.

Displaying the value of an interactive UI Slider

How to do it...

To create a UI Slider and display its value on the screen, follow these steps:

  1. Create a new 2D project.
  2. Add a UI Text GameObject to the scene with a Font size of 30 and placeholder text such as slider value here (this text will be replaced with the slider value when the scene starts).
  3. In the Hierarchy panel, add a UI | Slider game object to the scene—choose the menu: GameObject | UI | Slider.
  4. In the Inspector tab, modify settings for the Rect Transform to position the slider on the top-middle part of the screen and the text just below it.
  5. In the Inspector tab, set the Min Value of the slider to 0, the Max Value to 20, and check the Whole Numbers checkbox, as shown here:
    How to do it...
  6. Create a C# script class called SliderValueToText, containing the following code, and add an instance as a scripted component to the GameObject called Text:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class SliderValueToText : MonoBehaviour {
      public Slider sliderUI;
      private Text textSliderValue;
    
      void Start (){
        textSliderValue = GetComponent<Text>();
        ShowSliderValue();
      }
    
      public void ShowSliderValue () {
        string sliderMessage = "Slider value = " + sliderUI.value;
        textSliderValue.text = sliderMessage;
      }
    }
  7. Ensure that the Text GameObject is selected in the Hierarchy. Then, in the Inspector view, drag the Slider GameObject into the public Slider UI variable slot for the Slider Value To Text (Script) scripted component, as shown here:
    How to do it...
  8. Ensure that the Slider GameObject is selected in the Hierarchy. Then, in the Inspector view, drag the Text GameObject into the public None (Object) slot for the Slider (Script) scripted component, in the section for On Value Changed (Single).

    Note

    You have now told Unity to which object a message should be sent each time the slider is changed.

    How to do it...
  9. From the drop-down menu, select SliderValueToText and the ShowSliderValue() method, as shown in the following screenshot. This means that each time the slider is updated, the ShowSliderValue()method, in the scripted object, in GameObject Text will be executed.
    How to do it...
  10. When you run the scene, you will now see a slider. Below it, you will see a text message in the Slider value = <n> form.
  11. Each time the slider is moved, the text value shown will be (almost) instantly updated. The values should range from 0 (the leftmost of the slider) to 20 (the rightmost of the slider).

    Note

    The update of the text value on the screen probably won't be instantaneous, as in happening in the same frame as the slider value is moved, since there is some computation involved in the slider deciding that an On Value Changed event message needs to be triggered, and then looking up any methods of objects that are registered as event handlers for such an event. Then, the statements in the object's method need to be executed in sequence. However, this should all happen within a few milliseconds, and should be sufficiently fast enough to offer the user a satisifyingly responsive UI for interface actions such as changing and moving this slider.

How it works...

You have added to the Text GameObject a scripted instance of the SliderValueToText class.

The Start() method, which is executed when the scene first runs, sets the variable to be a reference to the Text component inside the Slider item. Next, the ShowSliderValue() method is called, so that the display is correct when the scene begins (the initial slider value is displayed).

This contains the ShowSliderValue() method, which gets the value of the slider. It updates the text displayed to be a message in the form: Slider value = <n>.

You created a UI Slider GameObject, and set it to be whole numbers in the 0-20 range.

You added to the UI Slider GameObject's list of On Value Changed event listeners the ShowSliderValue() method of the SliderValueToText scripted component. So, each time the slider value changes, it sends a message to call the ShowSliderValue() method, and so the new value is updated on the screen.

Left arrow icon Right arrow icon

Key benefits

  • Built on the solid foundation of the popular Unity 4.x Cookbook, the recipes in this edition have been completely updated for Unity 5
  • Features recipes for both 2D and 3D games
  • Provides you with techniques for the new features of Unity 5, including the new UI system, 2D game development, new Standard Shaders, and the new Audio Mixer

Description

Unity 5 is a flexible and intuitive multiplatform game engine that is becoming the industry's de facto standard. Learn to craft your own 2D and 3D computer games by working through core concepts such as animation, audio, shaders, GUI, lights, cameras, and scripting to create your own games with one of the most important and popular engines in the industry. Completely re-written to cover the new features of Unity 5, this book is a great resource for all Unity game developers, from those who have recently started using Unity right up to game development experts. The first half of the book focuses on core concepts of 2D game design while the second half focuses on developing 3D game development skills. In the first half, you will discover the new GUI system, the new Audio Mixer, external files, and animating 2D characters in 2D game development. As you progress further, you will familiarize yourself with the new Standard Shaders, the Mecanim system, Cameras, and the new Lighting features to hone your skills towards building 3D games to perfection. Finally, you will learn non-player character control and explore Unity 5's extra features to enhance your 3D game development skills.

Who is this book for?

This book is for anyone who wants to explore a wide range of Unity scripting and multimedia features, and find ready-to-use solutions for many game features. Programmers can explore multimedia features, and multimedia developers can try their hand at scripting. *From intermediate to advanced users, from artists to coders, this book is for you, and everyone on your team! *It is intended for everyone who has the basics of using Unity, and a little programming knowledge in C#.

What you will learn

  • Immerse players with great audio, utilizing Unity 5 s audio features including the new Audio Mixer, ambient sound with Reverb Zones, dynamic soundtracks with Snapshots, and balanced audio via Ducking
  • Create better materials with Unity s new, physically-based, Standard Shader
  • Measure and control time, including pausing the game, displaying clocks and countdown timers, and even implementing “bullet timeâ€? effects
  • Improve ambiance through the use of lights and effects such as reflection and light probes
  • Create stylish user interfaces with the new UI system, including power-bars, clock displays, and an extensible inventory system
  • Save and load text and media assets from local or remote sources, publish your game via Unity Cloud, and communicate with websites and their databases to create online scoreboards
  • Discover advanced techniques, including the publisher-subscriber and state patterns, performance bottleneck identification, and methods to maximize game performance and frame rates
  • Control 2D and 3D character movement, and use NavMeshAgents to write NPC and enemy behaviors such as seek, flee, flock, and waypoint path following
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 05, 2015
Length: 570 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391362
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Oct 05, 2015
Length: 570 pages
Edition : 1st
Language : English
ISBN-13 : 9781784391362
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 164.97
Unity 5  Game Optimization
$48.99
Unity UI Cookbook
$54.99
Unity 5.x Cookbook
$60.99
Total $ 164.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Core UI – Messages, Menus, Scores, and Timers Chevron down icon Chevron up icon
2. Inventory GUIs Chevron down icon Chevron up icon
3. 2D Animation Chevron down icon Chevron up icon
4. Creating Maps and Materials Chevron down icon Chevron up icon
5. Using Cameras Chevron down icon Chevron up icon
6. Lights and Effects Chevron down icon Chevron up icon
7. Controlling 3D Animations Chevron down icon Chevron up icon
8. Positions, Movement and Navigation for Character GameObjects Chevron down icon Chevron up icon
9. Playing and Manipulating Sounds Chevron down icon Chevron up icon
10. Working with External Resource Files and Devices Chevron down icon Chevron up icon
11. Improving Games with Extra Features and Optimization Chevron down icon Chevron up icon
12. Editor Extensions Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(17 Ratings)
5 star 88.2%
4 star 5.9%
3 star 0%
2 star 5.9%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




real7a May 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It's a good practical book on Unity game development and in the real world nowadays practice goes to production is very fast :) I've started to read it half a Year ago and started with several games and VR projects very fast. So the review is partial and delayed and anyway :)In short it's strongly recommended to jump start and get some vision of the landscape of Unity development.The book is organized as a cookbook as titled "Unity 5.x Cookbook" and it's the series of tutorial lessons actually. Some of lessons are easy and kind of artificial and they are used to show core concepts and lead to real useful tasks.I liked the tutorial of map radar for the shooter game. I made it and even submitted errata that was accepted.There are a lot of more useful lessons there. If You have time to learn it's very good addition to Unity tutorials and official Unity documentation.
Amazon Verified review Amazon
Nicole.Garrow Jan 02, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very helpful in game making!
Amazon Verified review Amazon
ruben Dec 26, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Unity 5.x Cookbook By Ruben Oliva RamosI liked this book, it has a big deal that I could understand the objective of the book, I understood all the chapters, The book has a new content that we can develep our own development.This is an excelent book, because covers my needs in game programming.Ruben
Amazon Verified review Amazon
Tim Crothers Dec 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love that this book is jam packed with practical and useful examples. All of the example code, images and other files are a free download. Seems to me that just finding one or two of the recipes useful would justify the cost of the book. In my case I was able to adapt several of them for inclusion in my projects and gained a ton of value.
Amazon Verified review Amazon
Adam Maksym May 29, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Helpful Info..
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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela