In my game I have a simple click to move character. On GetMouseButtonDown(0) (when mouse is clicked) I want the character to move to the location of the click, as long as the click does not occur on a UI element.

That's simple enough, I can use if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())

However, in every GetMouseButton(0) case except when mouse is initially clicked (when mouse button is held down), I want to be able to move even if my mouse is positioned behind a UI element.

So let's say I have an inventory open. I do not want clicking on the inventory to move my character. But if I click somewhere else and begin to move my character, and then move my mouse cursor behind the inventory, I want the character to continue moving. That is why I can't just do if(Input.GetMouseButton(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()).

I also can't do if(Input.GetMouseButtonDown(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) || !Input.GetMouseButtonDown(0) && Input.GetMouseButton(0))

Using a counter to measure elapsed time and then doing something like if(Input.GetMouseButton(0) && timer > 0.2f) doesn't seem to solve the problem either because I never want to move if the click origin is on a UI object, despite how much time has elapsed.


1 Answer 1


What if you had a toggle that said whether the current click was started not over a UI element.

// class variable
bool clickNotOverUI;

if (Input.GetMouseButtonDown(0) && 
      !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())) {
    clickNotOverUI = true;
else if (Input.GetMouseButtonDown(0)) {
    clickNotOverUI = false;

if (Input.GetMouseButton(0) && clickNotOverUI) {
     // do whatever

There's a decent chance I forgot some piece of logic but the idea is there.

  • \$\begingroup\$ Yeah, this is one of those things I was thinking I would maybe have to do, but wasn't really sure if I needed to. Anyway, I'll try this kind of thing out. \$\endgroup\$ Jul 30, 2017 at 12:39
  • \$\begingroup\$ Cool so this works. Toggling a bool based on the click origin is more elegant than I had it in my head haha. \$\endgroup\$ Jul 30, 2017 at 12:50
  • \$\begingroup\$ Glad it worked! \$\endgroup\$
    – elaid
    Jul 30, 2017 at 14:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .