Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to know the area name that agent is stepping?

Discussion in 'Navigation' started by IntDev, Apr 7, 2015.

  1. IntDev

    IntDev

    Joined:
    Jan 14, 2013
    Posts:
    152
    The agent go by many areas, like walkable, street, etc. How can I know the area it is currently stepping?
     
  2. Jakob_Unity

    Jakob_Unity

    Joined:
    Dec 25, 2011
    Posts:
    269
    Use the NavMeshAgent.SamplePathPosition api:

    Code (csharp):
    1. // SampleGround.cs
    2. using UnityEngine;
    3. #if UNITY_EDITOR
    4. using UnityEditor;
    5. #endif
    6.  
    7. [RequireComponent (typeof (NavMeshAgent))]
    8. public class SampleGround : MonoBehaviour {
    9.    NavMeshAgent agent;
    10.    NavMeshHit hit = new NavMeshHit();
    11.  
    12.    void Start () {
    13.      agent = GetComponent<NavMeshAgent> ();  
    14.    }
    15.    
    16.    void Update () {
    17.      // sample directly under agent
    18.      agent.SamplePathPosition(NavMesh.AllAreas, 0.0f, out hit);
    19.      Debug.Log ("Agent is currently on " + hit.mask);
    20.  
    21. #if UNITY_EDITOR
    22.      // in editor show the name too
    23.      var names = GameObjectUtility.GetNavMeshAreaNames ();
    24.      for (var i = 0; i < names.Length; ++i)
    25.      {
    26.        int mask = 1 << NavMesh.GetAreaFromName(names[i]);
    27.        if ((hit.mask & mask) != 0)
    28.        {
    29.          Debug.Log (".. that's \"" + names[i] + "\"");
    30.        }
    31.      }
    32. #endif
    33.    }
    34. }