Raycast needs to hit GUI

Ok,

I’m making a RTS/Castle Builder. I want to be able to click on a building and a dialogue box to come up. I already have code that RaycastAlls where ever the mouse is and gets that position. I can click on the buildings and it works. That’s not the problem.

The problem is I have no way of detecting if I’m hitting GUI. I’m using Daikon Forge of my GUI system. Right now, if I click on the GUI, I can still select an object behind the GUI. I want the GUI to be detected by the RaycastAll, so if I Raycast a GUI element I won’t select a building. How can I get the GUI to be detected by a RaycastAll?

EDIT:

Thank you for all the great responses! I really appreciate it. But I went to Daikon Forge’s forum and found out that they have a function to detect that: dfInputManager.ControlUnderMouse. Thanks anyway guys!

  1. Use GUIUtility.hotcontrol
  2. Call Event.current.Use immediately after any button is pressed
  3. Call return at the end of the button pressing code
  4. For non-click raycast blocking, only call raycasts if a boolean “overGUI” is set to false. Set it to true if the mouse cursor is inside a GUI Rectangle (using Rect.Contains). Set it to false in the LateUpdate function. Works perfectly.

GUIUtility.hotControl is the method I use. Its an int that tells you if the user is currently clicking on a control. Use an if statement to bypass your raycast code if hotControl !=0. Its more efficient not to do the raycast in the first place if you don’t need it.

An alternative, but not as efficient method is to place a collider behind your GUI element. If that collider is hit you then ignore the rest of the raycast. Of course you have already paid the performance cost for the raycast at this point.

you can’t do that with Raycast.

you have to check every gui component when you click somewhere on the gui.

then set a boolean (for example ‘mouseOnGui’) to true.

when you select a object first check if ‘mouseOnGui’ is false.

I have written a gui system with component based mouseListeners etc.

that would make it realy easy.
http://xumbu.org/unity3d/user-interface/doc

a newer version of my gui system even handles raycasting