Manually Trigger UI Navigation in Code

I can’t seem to find this in the UI Scripting API or anywhere else obvious, but is there a way to trigger UI navigation manually through script?

I’m working with a custom input device and I’d like to be able to functionally do this:

  1. User hits “down” on input device
  2. UI selects whatever Unity has set
    for the down navigation option, auto
    nav or otherwise.

That would spare me from having to setup my own nav relationship between elements and traverse it with SetSelectedGameObject.

Someone from the Unity Discord helped me come up with this solution. Works flawlessly.


using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(EventSystem))]
public class NavigationInjector : MonoBehaviour
{
    EventSystem eventSystem;

    private void Awake()
    {
        eventSystem = GetComponent<EventSystem>();
    }

    public void Move(MoveDirection direction)
    {
        AxisEventData data = new AxisEventData(EventSystem.current);

        data.moveDir = direction;

        data.selectedObject = EventSystem.current.currentSelectedGameObject;

        ExecuteEvents.Execute(data.selectedObject, data, ExecuteEvents.moveHandler);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.PageDown))
            Move(MoveDirection.Down);

        if (Input.GetKeyDown(KeyCode.PageDown))
            Move(MoveDirection.Up);
    }
}