Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to get currently focused element?

Discussion in 'UI Toolkit' started by Gekigengar, Oct 13, 2022.

  1. Gekigengar

    Gekigengar

    Joined:
    Jan 20, 2013
    Posts:
    705
    So, how to get currently focused element?
     
  2. Sebioff

    Sebioff

    Joined:
    Dec 22, 2013
    Posts:
    218
    I needed this too recently and couldn't find a simple way, but this seems to work:

    Code (CSharp):
    1. public static Focusable getFocusedElement()
    2. {
    3.     EventSystem eventSystem = EventSystem.current;
    4.     if (eventSystem == null)
    5.     {
    6.         return null;
    7.     }
    8.  
    9.     GameObject selectedGameObject = eventSystem.currentSelectedGameObject;
    10.     if (selectedGameObject == null)
    11.     {
    12.         return null;
    13.     }
    14.    
    15.     PanelEventHandler panelEventHandler = selectedGameObject.GetComponent<PanelEventHandler>();
    16.     if (panelEventHandler != null)
    17.     {
    18.         return panelEventHandler.panel.focusController.focusedElement;
    19.     }
    20.  
    21.     return null;
    22. }
     
    Gekigengar likes this.
  3. Gekigengar

    Gekigengar

    Joined:
    Jan 20, 2013
    Posts:
    705
    Thanks, that’s neat!
     
  4. BusyRoots

    BusyRoots

    Joined:
    Jul 25, 2017
    Posts:
    40
    Another possibility is to register a callback to the
    FocusInEvent
    .
    (tested with Unity version 2022.3.2f1)

    Example for a
    Button
    :
    Code (CSharp):
    1. Button aButton = SomeButton
    2. aButton.RegisterCallback<FocusInEvent, Button>(OnListElementFocus, button);
    3.  
    4. void OnListElementFocus(FocusInEvent focusInEvent, Button button)
    5. {
    6.     Debug.Log($"focused element: {button.text}");
    7. }
    Here is the Unity manual page that I found helpful in this regard: https://docs.unity3d.com/Manual/UIE-Events-Handling.html