UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

ui

[UI Toolkit] Fix Keyboard/Gamepad Button Interaction on Submit

Solution

ui toolkitinput systemevent handlinguser interface

Unity 2021.3.x - Unity 6.3.x

Published Sun, Mar 22

Issue

 Detecting the InputActions.UI.Submit action for custom VisualElement components is inconsistent compared to native buttons. Standard buttons automatically trigger their clicked logic when focused and confirmed via keyboard or gamepad, while custom elements require manual registration of navigation-specific events to achieve parity.

Quick-Fix

To replicate native button interaction, register a callback for the NavigationSubmitEvent on any focusable VisualElement to capture keyboard and gamepad submit inputs.

Expand Analysis

Register a callback for the NavigationSubmitEvent on your visual element to replicate the clicked behavior for UI Toolkit buttons. This event dispatches when a UI.Submit action occurs, mirroring standard button behavior.

  1. Identify the specific VisualElement within your script.
  2. Set the focusable property to true to ensure the element can receive focus and navigation events.
  3. Invoke RegisterCallback<NavigationSubmitEvent> on the visual element.
  4. Pass a delegate or lambda to execute logic when the NavigationSubmitEvent is triggered.

Additional Tips

  • To fully mirror a standard button, register both a ClickEvent and a NavigationSubmitEvent to the same handler function.
  • Ensure your visual element has its pickingMode set to PickingMode.Position if mouse interaction is also required.
  • The NavigationSubmitEvent is specifically designed for the Submit action (e.g., Enter or Space keys) and is essential for gamepad accessibility.

Copy


using UnityEngine.UIElements;

public class CustomButtonBehavior : VisualElement
{
    public CustomButtonBehavior()
    {
        // Ensure the element can be focused for navigation events
        this.focusable = true;
        
        // Replicate button behavior for both mouse and navigation inputs
        this.RegisterCallback<ClickEvent>(evt => OnConfirmed());
        this.RegisterCallback<NavigationSubmitEvent>(evt => OnConfirmed());
    }

    private void OnConfirmed()
    {
        UnityEngine.Debug.Log("Custom Element Activated!");
    }
}

Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.