I have a click to move character that uses a Nav Mesh Agent and I want to ignore clicks that are made on UI elements. For example, I don't want clicking around in my inventory to move my player to the target under the inventory. The relevant part of the move script is very simple.

if (Input.GetMouseButton(0) && !playerHealth.isDead)
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit))
        navMeshAgent.destination = hit.point;

I would think that this is a common question raised among beginner developers or that it would be covered in beginner courses, but I can't seem to find the info I'm looking for when Googling around, so I'll ask it here.

So how do I get my Nav Mesh Agent to ignore clicks made on a particular UI element? How about ignoring clicks made to any and all UI elements? Thanks.

  • \$\begingroup\$ You can use LayerMask to avoid clicking UI elements. \$\endgroup\$ – Aditya Yadav Jun 22 '17 at 12:47
  • \$\begingroup\$ Thanks, I added a LayerMask and deselected UI. Are there further steps? It's still not behaving correctly. \$\endgroup\$ – embracethefuture Jun 23 '17 at 2:23
  • \$\begingroup\$ The Layer field of the Canvas in the inspector is set to UI as well, but my character still moves when I click on UI stuff. \$\endgroup\$ – embracethefuture Jun 23 '17 at 7:10

Two things

Change to this:

  • if (Input.GetMouseButton(0) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())


  • Make sure your graphics have the option Raycast target set to true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.