- Home /
Check if button is pressed
I'm attempting have the player take an action (fire a weapon, choose a waypoint) if any part of the screen is clicked, except if they have clicked the part of a screen that is a button. I can't seem to limit the action click to the non-button parts of the screen.
Here's an example:
if (GUI.Button (Rect(Screen.width*0.02,Screen.height*.02,Screen.width*0.1,Screen.height*0.1), "Move"))
{
waypointSet = "no";
viewMode = "overhead";
fireMode = "off";
}
if(Input.GetKeyDown(KeyCode.Mouse0) && viewMode == "ground" && fireMode == "on"){
Fire();
Debug.Log("Fire");
}
I've also tried:
if (GUI.Button (Rect (Screen.width*0.02,Screen.height*.02,Screen.width*0.1,Screen.height*0.1), "Move"))
{
waypointSet = "no";
viewMode = "overhead";
}
else if(Input.GetKeyDown(KeyCode.Mouse0) && viewMode == "ground"){
Fire();
Debug.Log("Fire");
}
Answer by Davidovich · Feb 09, 2014 at 05:51 PM
You could try checking GUIUtility.hotControl
This will be populated with the GUI element that the mouse is over, so if it's empty, you're not over any GUI elements.
if (GUI.Button(Rect(Screen.width*0.02,Screen.height*.02,Screen.width*0.1,Screen.height*0.1), "Move"))
{
waypointSet = "no";
viewMode = "overhead";
fireMode = "off";
}
if(Input.GetKeyDown(KeyCode.Mouse0) && GUIUtility.hotControl == 0 && viewMode == "ground" && fireMode == "on"){
Fire();
Debug.Log("Fire");
}
I thought you had it there, but I tried it and it didn't work for some reason. I logged GUIUtility.hotControl in the GUI.Button if statement, and it logged 0 for some reason. I assume it has to equal something other than 0 for it to work.
I thought about checking mouseover, but I realized that I want to build this for mobile, so I don't imagine that will not work.
Looks like I'm wrong. I logged the hotControl outside of the GUI.Button if statement (but within onGUI) and it is registering a number. I think it just isn't fast enough. I may have to build a delay into the firing script.
I moved it from onGUI to Update and it now works. Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613133018im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Button Particle Emission 1 Answer
Get numeric key 4 Answers
GetKey and GetKeyDown are always registered? [Answered] 2 Answers
Trouble getting key down to work 1 Answer
GetKeyDown Enter button not working 1 Answer