I know this has been asked before but no clear resolution has been found.
I have a gui button and when I click on it, another script processes the fact that I clicked on the world behind the button.
I need to ignore mouse clicks in that other script if the mouse is clicking on the button.
Does anyone know a good way to do this?
This has been raised here:
but so far the only solution seems to be hacks involving setting a variable to true when a button is clicked and clearing it every frame and then testing that variable before processing any other mouse input.
The problem I seem to have with that is that other objects are Updated before the OnGui() is called (strange because those threads claim that doesn’t happen.)
If I put a Debug.Log() in the OnGui() and the Update() (and I’ve tried LateUpdate() as well), the log prints:
Update
OnGui
So the update processes the mouse click before the OnGui can determine that its over a button.
The best way to avoid this problem is to check if the mouse pointer is inside any “forbidden” rectangle before processing the mouse click:
function OverGui(): boolean { // return true if in forbidden region
var mouse = Input.mousePosition;
return gRect1.Contains(mouse) || gRect2.Contains(mouse) ||
gRect3.Contains(mouse) || gRect3.Contains(mouse);
}
function Update(){
if (!OverGui() && Input.GetMouseButtonDown(0)){
// click was not over gui: do what you want
}
}
The “forbidden” rectangles can be the same used in your GUI code to define the buttons - just define them as variables, like this:
var gRect1 = Rect(10,10,200,60);
var gRect2 = Rect(240,10,200,60);
var gRect3 = Rect(10,130,200,60);
var gRect4 = Rect(240,130,200,60);
function OnGUI(){
if (GUI.Button(gRect1,"Button1")) ...
if (GUI.Button(gRect2,"Button2")) ...
If functions in other scripts need to do the GUI test, declare the function and the rects as static, so you can easily access it from everywhere.