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...
- 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.
- 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.
- 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.
- 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:
- 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.
- Double-click on the script in order to open it in MonoDevelop.
- 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 anotherusing
clause. Therefore, at the beginning of our script, we need to get these:using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine; using System.Collections;
- 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;
- 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 theUpdate()
function in the following way:public void Update() if (Input.GetKeyDown (key)) { EventSystem.current.SetSelectedGameObject( this.gameObject); } }
- Now we can save the script and add it to one of the three buttons.
- 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:
- 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
- During the development of this script, we have seen different functions. The most important was the
GetKeyDown()
function. In fact, it allows you to detect whether a particular key is detected. You can find more information about it at http://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html. - However, this function needs a string as a parameter that specifies a key on our keyboard. You can find the complete list of the strings at http://docs.unity3d.com/ScriptReference/KeyCode.html.
- Finally, we have also used the
EventSystem
. This is very wide and can be used in different situations within Unity. Therefore, if you are looking for more information about it, you can refer to http://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.html.