- Home /
UI mouse click prevent default / stop propagation. (Block mouse events of other scripts)
Case: I have a UI (a part of the canvas) with buttons and sliders. In my scene there are also cameras with mouse pan by left mouse button.
Problem: When I use a slider the camera also pans.
Expected: Don't pan the camera when I use a UI slider. Don't process Input.GetMouseButtonDown
on other scripts, when I use the UI. Similar at html / javascript event.preventDefault()
.
Answer by Veetha · Feb 26, 2020 at 02:48 PM
It is an older question but sure will someone appreciate an answer... One of possible solutions is to make raycast test of a ui item. Modify your camera-panning method like this:
if ( Input.GetMouseButtonDown( 0 ) ) {
GraphicRaycaster gr = FindObjectOfType<GraphicRaycaster>();
PointerEventData ped = new PointerEventData(null);
ped.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
gr.Raycast(ped, results);
if (results.Count == 0) {
PerformCameraPanning();
}
}
This way camera pans only in case no UI item was found in the way of the mouse current position.
Ps: I believe GraphicRaycaster component is added automatically to the UI root GameObject as soon as an Image component is added.
Answer by jon_underwood · Apr 21, 2020 at 11:06 AM
Hey @Domvel Jason Weimann on YouTube has a great solution https://www.youtube.com/watch?v=rATAnkClkWU you'll need line 2 and lines 8 to 11 from the script he shows
Answer by cheonganlee · Aug 26, 2020 at 01:42 AM
For Unity 2019, use EventSystem.current.IsPointerOverGameObject().
Your answer
![](https://koobas.hobune.stream/wayback/20220612180447im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to detect click on naked panel? 1 Answer
Hide cursor and stop interaction 1 Answer
Get button under mouse 1 Answer
How can I detect a right-click on my UI button? 1 Answer
Get Global PointerEventData 1 Answer