How to block a Raycast with GUI-Elements

It’s simple as the image shows, has someone an anwer?

Greets, Felix

The Unity GUI system operates independently from Physics/raycasts. Before running a raycast, check the mouse position against the rects of your GUI elements. If the mouse position overlaps any GUI element rects, don’t do the raycast.

Thank you very much!
But there is another problem now …
The Code:

Rect rect = new Rect(Screen.width-250,Screen.height-310,230,250);
			
			GUI.Box(rect,"Towers");
			
			if (rect.Contains(Input.mousePosition)){
        		overGUI = true;
    		}else{
				overGUI = false;
			}

The GUI.Box is at the right place (like the on the image above), but the Rect I am interacting with seems to be above the GUI.Box, how is that possible?

Thank you, Felix

GUI rects originate from the upper left, but mouse position originates from the lower left. Confusing, no?

Try:

Vector2 mouseGUIPosition = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if (rect.contains(mouseGUIPosition)) {
    ...

UUUUUH!
I tried something else, but it works perfectly on your way!
Thank you very much! And yes, it is really confusing with these different origins!

Felix

Happy to help! I’m glad it’s working.

An additional question: can I mark this thread as solved? Sorry I am new here :face_with_spiral_eyes:

I don’t think so. You can mark questions on unityAnswers as solved, but not the threads here. You can edit your original post to mention that there’s an answer below.

I’ve found out that GUIUtility.hotControl can solve this problem way better.

If GUIUtility.hotControl is 0 then that means no GUI element is being used.

GUIUtility.hotControl is useful, but it only tells you that a GUI element is active (pressed down). If you’re casting arbitrary rays (say from mouse position while hovering but not clicking anything), it doesn’t help. However, if the OP is only interested in mouse clicks then your suggestion might be just the ticket.