Book Image

Unity UI Cookbook

By : Francesco Sapio
Book Image

Unity UI Cookbook

By: Francesco Sapio

Overview of this book

With the increasing interest in game development, it's essential to design and implement a UI that reflects the game settings and shows the right information to the player. The Unity system is used to create complex and aesthetically pleasing user interfaces in order to give a professional look and feel to a game. Although the new Unity UI system is powerful and quite easy to use, by integrating it with C# scripts, it's possible to realize the potential of this system and bring an impressive UI to games. This guide is an invaluable collection of recipes if you are planning to use Unity to develop a game. Starting with the basic concepts of the UI components, we’ll take you all the way through to creating complex interfaces by including animations and dynamics elements. Based on real-world problems, these recipes will start by showing you how to make common UI elements such as counters and healthbars. You will then get a walkthrough of how to manage time using timers, and will learn how to format them. You will move on to decorating and animating the UI elements to vivify them and give them a professional touch. Furthermore, you will be guided into the 3D UI world and into HUD scripting. Finally, you will discover how to implement complex minimaps in the interface.
Table of Contents (17 chapters)
Unity UI Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Selecting buttons through the keyboard


Often in games, there are menus that have shortcuts as well. For example, if the player has to use a skill quickly, he needs an easier way to access it. In general, where there is the possibility within the UI to choose more than one selectable element, such as buttons and toggles, it is possible to select them using a keyboard shortcut.

This recipe will teach you how to detect when a key is pressed and select a specific UI element by creating a script that is able to be generic enough to be placed on every UI element without changing the code.

How to do it...

  1. To begin, create a new panel. Right-click on Hierarchy panel and then go to UI | Panel. We can also rename it to keep the project names ordered.

  2. Next, we need to create a button inside the panel. We can do this by right-clicking on the panel and then navigating to UI | Button.

  3. In order to better see, which button is currently selected, let's change some properties of the Button (Script) component. For instance, we could choose a different color for Normal Color, Highlighted Color, and Pressed Color. In this example, let's set Highlighted Color to red and Pressed Color to green, and leave Normal Color as white. Finally, we also need to change Navigation to Vertical.

  4. In order to have the ability to choose among different buttons, we need different buttons in the scene. We can achieve this by duplicating the button. This can be done by pressing Ctrl + D and then placing the duplicated buttons below the original one. Rename the first of these to Button 1 and the second to Button 2. Repeat the same with the Text variable inside the Text (Script) component on the child of the button. As a result, we will be able to distinguish buttons on the screen as well. Finally, repeat this step at least two more times to get three buttons. Once we are done, our scene should look similar to the following:

  5. Now it's time to create our first script. To begin, in the Inspector, go to Add Component | New Script and name it ButtonThroughKeySelection. Then click on Create and Add. While doing this, ensure that the language selected is C Sharp.

  6. Double-click on the script in order to open it in MonoDevelop.

  7. Every time we work with some UI classes, we need to add a using clause on top of our script. This will ensure that we don't have any compilation error when the script is compiled by Unity. Furthermore, since we are also using events, we need to add another using clause. Therefore, at the beginning of our script, we need to get these:

    using UnityEngine.UI;
    using UnityEngine.EventSystems;
    using UnityEngine;
    using System.Collections;
  8. Moreover, we need to add a variable for the key that has been chosen. By doing this, we can set that variable in the Inspector:

    public class ButtonThroughKeySelection: MonoBehaviour {
    
      public string key;
  9. Since we don't need to set the initial variables, we can erase the Start() function. In order to implement the detection of the pressed key and change the selected button, we need to write the Update() function in the following way:

    public void Update()
      if (Input.GetKeyDown (key))
      {
         EventSystem.current.SetSelectedGameObject(
                  this.gameObject);
      }
    }
  10. Now we can save the script and add it to one of the three buttons.

  11. Next, set the Key variable with a string that represents a key, for example, space for the spacebar. Once we have done this, we should see something like this:

  12. Finally, we can click on the play button and see whether everything works. After our button is selected, by pressing the key bounded by the variable, we can move through the others with the arrow keys. However, if we re-press our key, which in this example is the spacebar, the selection returns to our button.

How it works...

To get started, we have created three buttons in the scene, which are our test buttons. We also had to change some of the buttons' properties in order to clearly see the effect that our script had on the buttons. Since we had distributed our buttons vertically, we set the Navigation variable to Vertical.

At the beginning of the script that we wrote, we added the using UnityEngine.UI; and the using UnityEngine.EventSystems; statements. The former needs to use UI elements inside our scripts, and it will be the most used through all the recipes of this book. The latter needs to use the Event System directly in our script.

As part of the next step in this recipe, we added a public string variable. It is public so that it can be set in the Inspector later. As a result, we can choose an arbitrary key to bind the specific button where the script is collocated.

Now, in the Update() function, we checked through if (Input.GetKeyDown (key)) to find out whether our key is pressed. In fact, the Input.GetKeyDown(string) function returns true if the key specified as a string is pressed, and false if it is not. It's important to remember that the Key variable is set in the Inspector, so it could change according to the design of our game. Check out the See also section for more information about key press detection.

Finally, if our key is pressed, we need to select a specific button. This can be done with the EventSystem.current.SetSelectedGameObject(this.gameObject); line. The first part, EventSystem.current, returns the current event system that is used. Then, we call on the SetSelectedGameObject(gameObject) function, which selects the game object passed as a parameter. In this case, we use this.gameobject, which is the game object where this script is attached, as well as the button that we want to select.

By keeping everything parametric, such as having a Key variable that can be set to every instance of the script, we are able to use this script on many buttons at one time and customize it differently without touching the code again.

See also