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.
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.