Changing Input with Unity Tab and Triggering Functions with Enter

Creating a Unity Script for UI Navigation with Tab and Enter Keys

Changing Input with Unity Tab and Triggering Functions with Enter

 The Unity game development platform offers various tools to manage interactions with user interfaces (UI). Among these tools are also code-based approaches that allow users to navigate and interact with UI elements. In this blog post, we will discuss how to create a C# script in Unity that enables UI navigation using the Tab and Enter keys.

Our Script Code for UI Navigation with Tab and Enter Keys

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class UIController : MonoBehaviour
{
    [SerializeField] private Selectable[] selectables;
    [SerializeField] private UnityEvent onEnterHandle;
    private int _selectedInput;

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Tab) && Input.GetKeyDown(KeyCode.LeftShift))
        {
            _selectedInput--;
            if (_selectedInput < 0)
                _selectedInput = selectables.Length - 1;
            selectables[_selectedInput].Select();
        }
        else if (Input.GetKeyDown(KeyCode.Tab))
        {
            _selectedInput++;
            if (_selectedInput > selectables.Length - 1)
                _selectedInput = 0;
            selectables[_selectedInput].Select();
        }

        if (Input.GetKeyDown(KeyCode.Return))
            onEnterHandle?.Invoke();
    }

    /// <summary>
    /// Change selectable
    /// </summary>
    /// <param name="selectableIndex" />Target selectable
    public void SetSelectedInput(int selectableIndex) => _selectedInput = selectableIndex;
}

This script controls an array of Selectable elements (a generic class for UI elements). The Update() function listens for keyboard input and selects the next or previous Selectable element when the Tab key is pressed. When the Enter key is pressed, it triggers the specified UnityEvent. 

To use this script, add an empty GameObject to your Unity scene and add the UIController component to it. Then, in the Inspector panel of the UIController component, drag and drop the UI elements into the selectables array and specify the event you want to trigger when the Enter key is pressed. 

This script allows keyboard navigation and interaction with user interfaces in Unity. This can be very useful in a Unity project that contains game menus, options menus, or any user interface.