Search icon CANCEL
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 UI Cookbook

You're reading from   Unity UI Cookbook Over 60 recipes to help you create professional and exquisite UIs to make your games more immersive

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher Packt
ISBN-13 9781785885822
Length 284 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Francesco Sapio Francesco Sapio
Author Profile Icon Francesco Sapio
Francesco Sapio
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. UI Essentials 2. Implementing Counters and Health Bars FREE CHAPTER 3. Implementing Timers 4. Creating Panels for Menus 5. Decorating the UI 6. Animating the UI 7. Applying Runtime Customizations 8. Implementing Advance HUDs 9. Diving into 3D UIs 10. Creating Minimaps 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:
    How to do it...
  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:
    How to do it...
  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

lock icon The rest of the chapter is locked
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 €18.99/month. Cancel anytime