Hey guys, I’ve been trying to figure out how block clicks in my game scene with UI objects, but I’m running into problems.
I’ve set up this little debug code here
if( Input.GetMouseButtonDown(0) )
{
if(EventSystem.current.IsPointerOverGameObject())
{
Debug.Log ("Clicked on UI");
}
else
{
Debug.Log ("Clicked on Space");
}
}
This is running in the update function, and whenever I click in the game scene, even when it’s not over the UI, unity returns “Clicked on UI”. I have a UI Canvas that covers the entire screen, and an inactive UI Panel
that covers the game screen, but I have a CanvasGroup
on that panel with Interactable and Blocks Raycasts
set to false
when it’s deactivated.
If anyone can help me understand why IsPointerOverGameObject
is always returning true
I’d greatly appreciate it.
If you’re like me and going crazy that IsPointerOverGameObject() always returns true, try this solution instead:
if (EventSystem.current.currentSelectedGameObject == null) {
// This code will not run if you clicked the UI
}
This worked great for me, so I ignore any clicks which is on the UI.
Another reason it might always return true, is if you check it when you’re not clicking, but the solution above has worked best for me.
Good luck!
Check the Event Mask
in the Physics Raycaster
on your camera. IsPointerOverGameObject()
will return true
if the mouse is over any objects on those layers.
If you only want to check for the UI layer, make sure that only UI is checked.
I think this should solve your problem but I’ll explain what I needed it for first.
My issue was that I was using OnMouseDown()
on elements in my scene to hide my interface but since some buttons in my interface were in front of those objects the Raycast would ignore the button completely and click the scene object, hiding the UI.
The solution was to put this on my scene objects (not the buttons).
void OnMouseDown()
{
bool blockedByInterface = EventSystem.current.IsPointerOverGameObject();
if (blockedByInterface == false)
{
//Hide UI
}
}
Another solution I believe is just to check the blocks Raycast option on your interface elements but it seemed easier to me to just stick this script on my scene objects instead.