Search Unity

Unity UI Manually Trigger Navigation Events in Script?

Discussion in 'UGUI & TextMesh Pro' started by eshan-mathur, Apr 23, 2020.

  1. eshan-mathur

    eshan-mathur

    Joined:
    Nov 22, 2011
    Posts:
    118
    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`.
     
    MaxIzrinCubeUX likes this.
  2. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    You probably need a custom Input Module.

    You can take the StandaloneInputModule as a reference and probably just need to rewrite
    GetRawMoveVector()
    .
     
  3. eshan-mathur

    eshan-mathur

    Joined:
    Nov 22, 2011
    Posts:
    118
    @Fenrisul on the Unity Discord helped me solve it with this - it works flawlessly!

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.EventSystems;
    3.  
    4. [RequireComponent(typeof(EventSystem))]
    5. public class NavigationInjector : MonoBehaviour
    6. {
    7.     EventSystem eventSystem;
    8.  
    9.     private void Awake()
    10.     {
    11.         eventSystem = GetComponent<EventSystem>();
    12.     }
    13.  
    14.     public void Move(MoveDirection direction)
    15.     {
    16.         AxisEventData data = new AxisEventData(EventSystem.current);
    17.  
    18.         data.moveDir = direction;
    19.  
    20.         data.selectedObject = EventSystem.current.currentSelectedGameObject;
    21.  
    22.         ExecuteEvents.Execute(data.selectedObject, data, ExecuteEvents.moveHandler);
    23.     }
    24.  
    25.     private void Update()
    26.     {
    27.         if (Input.GetKeyDown(KeyCode.PageDown))
    28.             Move(MoveDirection.Down);
    29.  
    30.         if (Input.GetKeyDown(KeyCode.PageDown))
    31.             Move(MoveDirection.Up);
    32.     }
    33. }
     
  4. radiatoryang

    radiatoryang

    Joined:
    Jul 7, 2014
    Posts:
    19
    thanks to this thread, I wrote an all-purpose function for forcing a deselect input event on a UI object (like a button or event trigger)

    Code (CSharp):
    1. public void Deselect(GameObject obj) {
    2.     ExecuteEvents.Execute(obj, new PointerEventData(EventSystem.current), ExecuteEvents.deselectHandler);
    3. }