- Home /
How to block clicks in UI from interacting with background?
So I have a circle in 2d which I'm rotating by just dragging to mouse around on the background(everywhere basically). But I made a UI now with a draggable button, and whenever I click or drag the button, the circle in the background also responds to it. How can I stop this?
Appreciate all suggestions.
Answer by SirPaddow · Jun 04, 2019 at 06:27 AM
The EventSystem created along with your Canvas lets you do that:
if (!EventSystem.current.IsPointerOverGameObject())
{
// Cursor is not over UI
}
https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
That doesn't really work in my case, but I'm not sure why. The circle is still rotating when clicking the ui, although it's more laggy. I think it might be partly because my button is draggable on the x-axis, so when my pointer leaves the button even for a frame, the circle gets focus? Edit: After testing for awhile, I can for certain say that it's because the pointer might be outside the button when dragging. Any way around this? Edit2: Circle still detects even just clicks on UI. IsPointerOverGameObject feels very random...
Indeed, it is probably every time your cursor leaves the ui. I can't think of a solution provided by Unity, but maybe you can implement your own solution, something like:
public class $$anonymous$$yGame : $$anonymous$$onoBehaviour
{
private bool draggingUI = false;
public void Update()
{
if (!draggingUI && !EventSystem.current.IsPointerOverGameObject()) // You are not dragging and your cursor is not over a UI element
{
// Check input and rotate your circle
}
}
// Not sure how you manage drag and drop in UI, but I guess you should have functions like this
public void OnDragUI()
{
draggingUI = true;
// do stuff
}
public void OnDropUI()
{
draggingUI = false;
// do stuff
}
}
Your answer
Follow this Question
Related Questions
OnGui (c#) Question, want to make a button that opens a box 1 Answer
How do i press multiple buttons at once in a single swipe 0 Answers
why won't my add button script work?!? (help appreciated) 2 Answers
Is there a way to move a button to a random location after a certain number of clicks? 1 Answer