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\$
3
  • \$\begingroup\$ You can use LayerMask to avoid clicking UI elements. \$\endgroup\$ Jun 22, 2017 at 12:47
  • \$\begingroup\$ Thanks, I added a LayerMask and deselected UI. Are there further steps? It's still not behaving correctly. \$\endgroup\$ Jun 23, 2017 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\$ Jun 23, 2017 at 7:10

1 Answer 1

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\$
0

You must log in to answer this question.

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