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 now! 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
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 5.x Cookbook

You're reading from   Unity 5.x Cookbook More than 100 solutions to build amazing 2D and 3D games with Unity

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher Packt
ISBN-13 9781784391362
Length 570 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Core UI – Messages, Menus, Scores, and Timers FREE CHAPTER 2. Inventory GUIs 3. 2D Animation 4. Creating Maps and Materials 5. Using Cameras 6. Lights and Effects 7. Controlling 3D Animations 8. Positions, Movement and Navigation for Character GameObjects 9. Playing and Manipulating Sounds 10. Working with External Resource Files and Devices 11. Improving Games with Extra Features and Optimization 12. Editor Extensions 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:

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:

You have been reading a chapter from
Unity 5.x Cookbook
Published in: Oct 2015
Publisher: Packt
ISBN-13: 9781784391362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime