# Click to move - get NavMesh layer

I'm using NavMesh, and NavMeshAgent for my character movement and Pathfinding.

I made a testing NavMesh with 2 area layers:

0 = Walkable 3 = Water.

In have a click to move script, and i need to get the ID of the NavMesh Area where the player clicked. I tried to get the ID of the layer where the player clicked, using NavMeshHit.mask but is always resulting 0, even if I click where the NavMesh area ID is 3.

From Unity documentation:

Mask specifying NavMesh area at point of hit.

Script:

RaycastHit hit;
NavMeshHit nHit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
bool hasHit = NavMesh.Raycast (this.transform.position, ray.direction, out nHit, NavMesh.AllAreas);
if (hasHit) {
Debug.Log ("Area ID: " + nHit.mask);
targetPosition = hit.point;
}
}

• Which object is this script attached to? – LVBen Sep 13 '15 at 18:34
• It attached to my character. – Fr0z3n Sep 13 '15 at 18:39
• The raycast is going out of the camera and you are checking another raycast from player position. If the camera is even slightly away from the character - it can give you totally different hit point. – Candid Moon _Max_ Sep 17 '17 at 19:40

Your 2nd argument appears to be incorrect. The 2nd argument should be the point in which the ray intersected with the object that was clicked on.

Like this:

RaycastHit hit;
NavMeshHit nHit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, out hit)){
bool hasHit = NavMesh.Raycast (this.transform.position, hit.point, out nHit, NavMesh.AllAreas);
if (hasHit) {
Debug.Log ("Area ID: " + nHit.mask);
targetPosition = hit.point;
}
}

• It's not working, eve with a simple Debug.DrawLine() the ray starts at the camera Position, and hit the wrong position. Doesn't matter where i click, the Ray hits the same position. So there must be something wrong. And yes, the NavMesh.Raycast must match the Physic Raycast. – Fr0z3n Sep 13 '15 at 18:56
• docs.unity3d.com/ScriptReference/NavMesh.Raycast.html I think that the second parameter is wrong, but if i use the hit.position the raycast show correctly, but doesnt return true. – Fr0z3n Sep 13 '15 at 18:59
• It should start at the camera position. The direction should be towards the object that was clicked on. – LVBen Sep 13 '15 at 18:59
• oh, you are probably right. – LVBen Sep 13 '15 at 19:01
• I updated my answer. You want to use the point that the ray hit as the 2nd argument and the character(or navAgents)'s position as the 1st argument. – LVBen Sep 13 '15 at 19:06