Book Image

Unity 5.x Cookbook

Book Image

Unity 5.x Cookbook

Overview of this book

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.
Table of Contents (20 chapters)
Unity 5.x Cookbook
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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:

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:

  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:

  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:

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:

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:

  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:

  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 .

  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: