I’m using IsPointerOverGameObject() inside OnMouseDown() to detect whether the player is clicking/touching a GUI button that happens to be over the game object. If that’s the case, the function ignores the remainder of the code in OnMouseDown() by immediately returning:
void OnMouseDown()
{
// Detect mouse event
if (EventSystem.current.IsPointerOverGameObject())
{
print("return mouse");
return;
}
// Detect touch event
foreach (var touch in Input.touches)
{
if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
print("return touch");
return;
}
}
// Other code...
}
In the editor, this works as expected when clicking a GUI button over the game object: the function prints “return mouse” and returns. On my Android device, the GUI object is interacted with, but the OnMouseDown() function doesn’t return!
/// <returns>true if mouse or first touch is over any event system object ( usually gui elements )</returns>
public static bool IsPointerOverGameObject(){
//check mouse
if(EventSystem.current.IsPointerOverGameObject())
return true;
//check touch
if(Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began ){
if(EventSystem.current.IsPointerOverGameObject(Input.touches[0].fingerId))
return true;
}
return false;
}