5
\$\begingroup\$

I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non-rectangle shaped UI that's pretty difficult.

I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size.

Note: Canvas Group does not apply to physics.raycast

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

The physics raycast is a different system and doesn't see UI elements. So you can not cause the UI to block physics raycasts. However you have options:

What you can do is cast two rays. One raycast for your UI elements and one for your physics objects. If your UI raycast detects a UI element, you know a UI element is in the way, and you shouldn't cast your physics ray cast.

Or, you can use the event system (which is already casting a ray into the UI elements) to tell you if you're over a UI element:

UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()

IsPointerOverGameObject does respond to Canvas Group, so make sure to disable the raycast block if your UI element is invisible (if you don't want to detect invisible UI elements).

\$\endgroup\$
0
\$\begingroup\$

In the old Immediate Mode GUI (so not the newer canvas-based UI which indeed should use IsPointerOverGameObject()) you can use GUIUtility.hotControl.

Here is a quick example that showcases both the old and the new UI blocking clicks to some colliders: enter image description here

Example Source: https://gist.github.com/JohannesMP/3d3882e6bd57e378412fa5d7d95d0c47

\$\endgroup\$

You must log in to answer this question.

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