Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question (EventSystem) currentSelectedGameObject gets nulled out on mouse click

Discussion in 'UGUI & TextMesh Pro' started by lafr3mdulo, Nov 1, 2023.

  1. lafr3mdulo

    lafr3mdulo

    Joined:
    Oct 8, 2021
    Posts:
    10
    I'm using the UI EventSystem to capture UI events using the built-in interfaces.

    I have a MonoBehavior that handles inputs for a menu set up like this.
    Code (CSharp):
    1. public class MyMenuController : MonoBehaviour, ISubmitHandler, ICancelHandler, IMoveHandler
    2. {
    3.         private void Start()
    4.         {
    5.             EventSystem.current.currentSelectedGameObject = gameObject;
    6.         }
    7.  
    8.         // ISubmitHandler
    9.         public void OnSubmit(BaseEventData eventData)
    10.         {
    11.             // Handle Submit
    12.         }
    13.  
    14.         // ICancelHandler
    15.         public void OnCancel(BaseEventData eventData)
    16.         {
    17.             // Handle Cancel
    18.         }
    19.  
    20.         // IMoveHandler
    21.         public void OnMove(AxisEventData eventData)
    22.         {
    23.             // Handle Nav
    24.         }
    25. }
    26.  
    It works fine until I click on another UI element that implements the IPointerClickHandler interface.
    Code (CSharp):
    1. public class MyUIElement : MonoBehaviour, IPointerClickHandler
    2. {
    3.     public void OnPointerClick(PointerEventData eventData)
    4.     {
    5.         // Handle Click
    6.     }
    7. }
    When I click, the click-handling code runs, but EventSystem.current.currentSelectedGameObject gets set to null in the process, so my menu stops receiving input events. I've been working around this with a hack that reassigns my menu to EventSystem.current.currentSelectedGameObject after clicking. It works, but feels wrong.

    Are there some best-practices or a pattern for handling this type of interaction? I'm guessing I'm not doing this the best way..