- Home /
Differentiate between button click and screen click - Pause button not working
Hello, I have a problem for several hours now. I have a pause button to pause my game. The game fires a projectile on a mouse click. Every time I click on the pause button, the projectile is fired before the pause menu opens. The Click-Event on the button sets a boolean to false, so the Input should not be detected. Things I tried so far:
Creating a bool to disable Input
Setting time-scale to 0 (not working, pause menu not showing)
Using LateUpdate or OnGUI-method instead of (Fixed)Update
Debug.Log - tests showed, that the click event is earlier called in the (Fixed)-Update method than the button recognizes the click. What can I do to differentiate the clicks?
Answer by FortisVenaliter · Jan 27, 2017 at 10:26 PM
What you can do is have the game check to see if the mouse is over any UI elements (like buttons) before firing. The RectTransformUtility class has a function to see if a RectTransform contains a screen point that is perfect for this situation. You'll just need an array or something of possible mouse blockers.
Thank you! I researched on this, and I found something that I can use. I tested it, it works perfectly fine.
private bool IsPointerOverUIObject()
{
var eventDataCurrentPosition = new PointerEventData(EventSystem.current)
{
position = new Vector2(Input.mousePosition.x, Input.mousePosition.y)
};
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
In my click-event i just have to check the result of this method.
Answer by abhyudaystar · Sep 25, 2017 at 05:02 AM
Here is a function that is working very fine for me.
I found "UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()". This return a bool which can be used to differentiate between the clicks done in the screen area and the clicks done on the UI button.
Example:
if (Input.GetMouseButtonDown (0) && bulletCount > 0 && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) { BulletSpawn(); }
Cheers! :)
Answer by frankslater · Sep 25, 2017 at 07:08 AM
Just use OnPointerDown instead of OnMouseDown and you won't have the clicking through problem. No need to hack around like this and it will also work on mobile.
Your answer
Follow this Question
Related Questions
Simulate a mouse Click? 2 Answers
Trigger a Button Click 2 Answers
WebGL Input Manager reacting 0 Answers