need to block raycast with UI

When I click on my UI, my physics raycast also hits objects behind the UI.

I’ve tried this nifty piece of code:
if (!EventSystem.current.IsPointerOverGameObject(-1)) (with and without the “-1”).

The effects of which are to block all ray casts, anywhere on screen (not only on UI). I’m using panels to organize my UI elements. I’ve tried ticking all panels and UI elements off in the inspector while in play mode to see if any of them are specifically blocking ALL the ray cast, but even with every panel and UI elements off, all ray casts are blocked.

I’ve also tried adding canvasgroups (with block raycast ticked on), but these don’t block physics raycasts…

I’ve been reading a lot of posts on the subject, but haven’t found anything on this problem specifically…

if (Input.GetMouseButtonDown (0)) { // only if the mouse was NOT clicked over a UI element if (!EventSystem.current.IsPointerOverGameObject(-1)) { if (Physics.Raycast (ray, out hit)) { if (hit.transform.gameObject.tag == "theThingToHit") { DoSomething(); } } }

It’s kinda late but i just solved this issue in my game using exactly what you were trying to use… I tried to solve this months ago and have significant reason to believe that the solution didn’t work back then. But i did it the reverse way, because the UI buttons have their own click method unrelated to the controls in the game.

if (!EventSystem.current.IsPointerOverGameObject ()) {
if (Input.GetMouseButtonDown (0)) {

I apologize in advance for my bad English
If you have such a problem, that after switching to the UI interface menu and you are pushing objects behind the interface associated with raycast, I recommend adding a function in the script that detects when the ui interface is active, then deactivates the ray cast. This modification helped in my case and I wanted to share it for future users, I hope that I will help someone :slight_smile: