2
\$\begingroup\$

I have a canvas with a panel with set width / height inside. The canvas rendermode is set to ScreenSpace Overlay.

My clicks on the panel are falling through and hitting the game objects below triggering their mouse events.

enter image description here

The little green circle is a Sprite with the following event

  public void OnMouseDown() {
        Debug.Log("click");
        Vector3 newPos = Camera.main.WorldToScreenPoint (this.transform.position);
        newPos.x -= panel.GetComponent<RectTransform>().rect.width / 2.0f;
        newPos.y -= panel.GetComponent<RectTransform>().rect.height / 2.0f;

        panel.transform.position = newPos;
  }

I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?

\$\endgroup\$
2

1 Answer 1

1
\$\begingroup\$

You can try to use IsPointerOverGameObject to check if the mouse is over a UI element. Something like this:

public void OnMouseDown() {
        if (EventSystem.current.IsPointerOverGameObject()) return;

        Vector3 newPos = Camera.main.WorldToScreenPoint (this.transform.position);
        newPos.x -= panel.GetComponent<RectTransform>().rect.width / 2.0f;
        newPos.y -= panel.GetComponent<RectTransform>().rect.height / 2.0f;

        panel.transform.position = newPos;
  }

If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1); therefore when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it. For example:

private static bool IsPointerOverGameObject()
{
    #if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
        const int fingerId = 0;
    #else
        const int fingerId = -1;
    #endif

    return EventSystem.current.IsPointerOverGameObject(fingerId);
}
\$\endgroup\$
1
  • \$\begingroup\$ Hey thanks for your help with that. I was having trouble getting my head around the IsPointerOverGameObject() method but to try sum that up - place that function at the top of any code that handles mouse click on any non-UI components, the method will return true whilst over UI components. \$\endgroup\$
    – Marklar
    Commented Jan 8, 2017 at 10:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .