2
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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
3
\$\begingroup\$

Two things

Change to this:

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

and

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

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.