Can ONGUI Block Raycast ?

Hi

I try to create turn-base game and use raycast for select a monster
when I click at monster raycast cast a line from camera to a monster and get it as gameobject
then it will show ONGUI(this onguiScript is attached on the monster )
and if you click other gameobjects ONGUI will disable

my problem is when click on the ONGUI the raycast get a new object instead.

I would like to see when I click on the ONGUI it only do a method and raycast not pass the GUI but can click other area outside the GUI

please tell me if I explain not enough or wrote something wrong

3015680--225071--GUI.PNG

The answer to your question is yes, but you have to check for it in the code where you call your raycast.

However, take a step back, and stop using the OnGUI-based system. It’s the old system and has been basically deprecated for in-game code. (It is still used to write editor tools, custom inspectors, etc, which is probably the only reason it still exists in the engine.) No one writes code for it anymore, which is why, for example, I can’t remember what the function call is for OnGUI-based code to check if the pointer is over any UI element.

Use the new Unity UI system, which is much better, and in that system, the answer to this question is EventSystems.EventSystem.IsPointerOverGameObject.

Use the new UI system. OnGUI should be for editor scripting only.

The new UI system is quite efficient for handling raycast blocking.

Just for completeness sake:

If you are handling Raycasts yourself (which can be desirable if you have a ton of Colliders and only one script that cares if any one of them was clicked), and you absolutely have to use IMGUI UI elements, then you can use GUIUtility.hotControl to check if in the frame you got a click on a given object, the same click also hit an IMGUI control:

Sample Source Code: [Unity3D] How to check for UI blocking Raycasts · GitHub

2 Likes