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

How to get a click event from any arbitrary object?

Discussion in 'UGUI & TextMesh Pro' started by BonyYousuf, Dec 30, 2014.

  1. BonyYousuf

    BonyYousuf

    Joined:
    Aug 22, 2013
    Posts:
    110
    Hi,
    I have made a dropdown using 4.6. It works just fine now. However the dropdown doesn't close when I click somewhere else other than the dropdown. I have not been able to achieve this. I can close the dropdown if the dropdown itself was clicked or a value is selected. Now all I need is to get a click event from any arbitrary object. So whenever the dropdown is open and I click something other than dropdown, I can close the dropdown.

    any way to achieve this?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Old fashioned Input.GetMouseButtonUp?
     
  3. BonyYousuf

    BonyYousuf

    Joined:
    Aug 22, 2013
    Posts:
    110
    could you please give an example of that code so i know how to subscribe to that event?
     
  4. Sebioff

    Sebioff

    Joined:
    Dec 22, 2013
    Posts:
    218
    Code (CSharp):
    1. void Update() {
    2.     if (Input.GetMouseButtonUp(0) /* && mouse not over dropdown */) {
    3.         // close dropdown
    4.     }
    5. }
    There's no global "the mouse clicked somewhere" event, so you'll have to poll every frame like this on your dropdown element.

    The harder part is checking if the mouse is currently over your dropdown or anywhere else since as far as I know there's currently no way to get the UI element that's below the mouse pointer.
    You should be able to check if your dropdown is being hovered using RectTransformUtility.RectangleContainsScreenPoint (if you're using a "Screen Space - Overlay" canvas I think you can simply pass null for the camera parameter, although the docu doesn't mention this). If this doesn't work you could use IPointerEnterHandler/IPointerExitHandler to find out if the mouse is currently hovering your dropdown.
     
    Last edited: Dec 30, 2014
  5. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    Create a screen sized invisible area that is enabled behind your dropdown that will receive the click via an interface.

    Look at the RectBlocker code snippet here and implement the appropriate IPointer* interfaces.

    http://forum.unity3d.com/threads/recttransform-and-events.285740/
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    On further research there is an event trigger for deselect. This may be useful.