- Home /
Detect clicks on the screen but not on any button
Hi! I am developing android game and I want to display a menu (a canvas) that includes buttons. To get out of the menu and start the game, the user needs to tap anywhere on the screen. Now, in order to do so, I need to detect when the user clicks on a button (In that case, the game won't start) and when he clicks on the screen, without touching any button. There are also some text object on my canvas, Clicking on them is considered a click on the screen. Before I added the buttons to the canas, I had just checked on each update if there is a new Touch (using Input.GetTouches() -> touch.begin). In that case, after I had added the buttons, when a button was clicked, the touch was detected and the menu disappeared. How can I know when the user clicks on the buttons, and when he clicks on the rest of the screen? Thank a lot!
why not simply make all the buttons set a bool variable to true. then when you get your overall screen touch only apply it if the bool from the buttons is false?
Answer by saschandroid · Aug 21, 2018 at 06:59 AM
You probably want this: EventSystem.IsPointerOverGameObject
// Check if there is a touch
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
// Check if finger is over a UI element
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("Touched the UI");
}
}
This works both ways.... To detect touches on button bit not screen: if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { // Check if finger is over a UI element if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { Debug.Log("Touched the UI"); } else { //Code goes here } }
Answer by Reivaj28 · Aug 21, 2018 at 09:39 AM
You have two scripts, one for your button and the other for a GameObject that occupies the whole screen. When the button is clicked, is called the OnClick() method. Now, for making the Screen clicked you must do the following thing in the script of the GameObject:
public class ScreenScript : MonoBehaviour {
private void OnMouseDown() {
//Do something when the screen is clicked
}
}