So I’ve researched this a bit on the forum and the answers but, so far I haven’t seen a good solution to this problem. In the current game I am working on, mouse clicks/touches cause raycasts which control units, however those raycasts still occur even when a GUI button or other GUI item is above where the clicks/touches are occuring.
Is there any way to stop a mouse click event or touch event from going through GUI elements? In javascript or flash it would be something like event.stopImmediatePropagation().
Also Event.current.Use() does NOT fix this issue as others have said it would.
Maybe it’s too late to answer this question but what i do in these cases is check if the mouse position is contained in some of the rectangles of my gui elements (in the OnGUI()). For example:
Considering that “new Rect” has the same coordinates and dimensions of some of your gui elements (a sidebar for example). The problem is that it limits you to use only square gui elements.
I’ve also been looking for an answer to this. My game does the same thing, raycasts to send a target position to the player. I’d rather not have to restrict my interface, but I guess that’s the only way to do it now. I think this thread summarizes this as a bug in Unity, that they want to fix. I hope they do soon.
I would consider toggling the raycasts on and off using OnMouseEnter, OnMouseExit, and OnMouseOver on the gui elements.If you use OnMouseOver, and test the alpha value of the pixel the mouse cursor is on, you won’t be restricted to rectangular elements.
I encountered a similar code-design issue when I first started working with Unity. Basically, what I ended up doing was creating an input manager class and wrapping all the necessary code in special function calls.
All my GUI code implemented a C# interface, and my manager kept a list of all active interfaces. All my world objects implement another interface designed to wrap all the mouse over/enter/exit/down… events and check to ensure they should be active.
Basically you would just be asking:
if ((List of GUI elements).Contains(Input location) == false){
// Do the raycast
}