Search Unity

Preventing EventSystem from losing focus

Discussion in 'UGUI & TextMesh Pro' started by qkjosh, Mar 7, 2018.

  1. qkjosh

    qkjosh

    Joined:
    Nov 29, 2015
    Posts:
    33
    Hi there. I'm working on a game that accepts both gamepad and mouse input. Unity's default behavior in EventSystem.cs's SetSelectedGameObject method is to deselect the previously selected object when you select something new. That's fine, except if you click outside of any UI element, the new target is null - there's nothing for it to select. When the player is on a menu screen, I want it to behave more like older console game where something must always have focus. I've seen autofocus approaches where you repeatedly check for the "nothing selected" state and select the previously selected UI element, but this causes flicker and re-triggers the select event.

    At this point, I've cloned the Unity UI source code and built my own version that prevents setting the event system's currently focused gameobject to null, but I'm a little wary of doing this. There are a few game specific things to fix if I go this route, but I wanted to know whether there was a better way of discarding pointerdown / click events. Something to stop event propagation like event.preventDefault in the web dev world.

    Here's what I've done, just for reference:
    Code (CSharp):
    1.  
    2.         public void SetSelectedGameObject(GameObject selected, BaseEventData pointer)
    3.         {
    4.             if (m_SelectionGuard)
    5.             {
    6.                 Debug.LogError("Attempting to select " + selected +  "while already selecting an object.");
    7.                 return;
    8.             }
    9.  
    10.             m_SelectionGuard = true;
    11.             if (selected == m_CurrentSelected)
    12.             {
    13.                 m_SelectionGuard = false;
    14.                 return;
    15.             }
    16.  
    17.             //Debug.Log("Selection: new (" + selected + ") old (" + m_CurrentSelected + ")");
    18.  
    19.             /* NEW: Return early if we're going into a state where no UI elements have focus */
    20.             if (selected == null)
    21.             {
    22.                 Debug.Log("Cannot select nothing");
    23.                 m_SelectionGuard = false;
    24.                 return;
    25.             }
    26.             /////////////////////////////////////////////////////////////////////////////
    27.  
    28.             ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.deselectHandler);
    29.             m_CurrentSelected = selected;
    30.             ExecuteEvents.Execute(m_CurrentSelected, pointer, ExecuteEvents.selectHandler);
    31.             m_SelectionGuard = false;
    32.         }
    33.  
     
    Last edited: Mar 7, 2018