Get NavMeshAgent current area

Hello,

I browsed the unity documentation for some time but i still can’t understand how to detect what area the Agent is in? Let’s say i have two areas: Walkable, Water both of them are accessible, how can i know when the agent is in eachone of these?

Thanks.

EDIT 1:

I have tried to do this:

		NavMeshHit navMeshHit;
		Debug.DrawRay(agent.transform.position, agent.transform.up * -5f);
		if(agent.Raycast(agent.transform.up * -5f, out navMeshHit))
		{
			print (navMeshHit.mask);
		}

It keeps giving me index 0 even i’m on a different area. What’s wrong?

You can try SamplePosition with a small range distance:

NavMeshHit navMeshHit;
if(NavMesh.SamplePosition(agent.transform.position, out navMeshHit, 0.1f, 0xFFFFFFFF)) {
     print (navMeshHit.mask);
}

Probably more efficiently, if the agent has a current path, you can:

    NavMeshHit navMeshHit;
    agent.SamplePathPosition(NavMesh.AllAreas, 0f, out navMeshHit);

Note that in both cases, the returned navMeshHit.mask is a bitset of areas, not a the index of a single area.

{
NavMeshHit hit;
NavMesh.SamplePosition(agent.transform.position, out hit, 0.1f, NavMesh.AllAreas);
int index = IndexFromMask(hit.mask);
Debug.Log("hit_: " + index);
}

    private int IndexFromMask(int mask)
            {
                for (int i = 0; i < 32; ++i)
                {
                    if ((1 << i) == mask)
                        return i;
                }
                return -1;
            }