Swallow mouse click if button pressed

I think there is a method or something to do this but I’m not sure.

In one of my scripts I use GetMouseButtonUp to detect if the left mouse button has been lifted from a previous press, this is so I can place a GameObject at the clicked position, but I have several buttons on the screen, and if I press one of the buttons I get a new GameObject at that position which I don’t want.

I’m sure there is a method/function that checks for a button press though the Event System, but I just cannot remember and would this block the GetMouseButtonUp event.

There may be more than one way, but in sort of similar circumstances, I"ve used “EventSystem.current.IsOverGameObject” or something like that (sure it’ll come up in the IDE)… which returns true if you’re over any object (accepting raycasts?) in the canvas, I think.

What I do is, quit using things like GetMouseButtonUp, and instead embrace the event system.

This means putting a big invisible Image object at the top (back) of your canvas hierarchy, so that it covers the whole screen, and then add an EventTrigger component to it. And then use the event triggers there to invoke whatever you want to happen in your scene when the mouse is clicked, dragged, etc.

The reason this works great is that, since this event trigger is part of the UI hierarchy and positioned behind everything else, it automatically ignores any clicks which are on closer UI elements like buttons, panels, etc.

1 Like

Hi @methos5k & @JoeStrout

Yeah a short while after I posted, I was searching for something else and I found EventSystem.current.IsOverGameObject, I was looking on posts here about the method, and on earlier version of unity < 5.0, it did not work in the update, but mine does, may be this is a fix they made.

void Update()
{
  if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
    return;
}

Normally I code my own Editors “External programs”, to help with creating programs/apps on unity e.g Map Editor and the like, but this time I felt it was better suited to create it in Unity, including saving the data to a xml file and porting that over to the client side software.

I know this editor is only going to be used by me, but it also nice to learn new tricks you never know when you need it, for further development purposes.

I usually use IPointer and the like, but I felt for this it was over kill so far, I’m not suffering, apart from the UI stuff, I’ve also made a sort of Navigation Drawer (native in android), to hide/unhide my interface, so I can drag my drawing around, basically on a full screen or there about.

JowStrout If I’ve miss interpreted what you are saying I’m sorry.

Thanks guys.

Glad ya got it working :slight_smile:

Nice