Search code examples
c#unity-game-enginenavmesh

NPC instantiate on Navmesh


I am trying to instantiate a NPC prefab on a NavMesh in a grid fashion. The prefab has the component NavMeshAgent and the NavMesh has been baked. I am getting the errors:

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)

and

"GetRemainingDistance" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:get_remainingDistance()

This using the following script on an empty GameObject placed over the NavMesh:

 // Instantiates a prefab in a grid

    public GameObject prefab;
    public float gridX = 5f;
    public float gridY = 5f;
    public float spacing = 2f;

    void Start()
    {
        for (int y = 0; y < gridY; y++)
        {
            for (int x = 0; x < gridX; x++)
            {
                Vector3 pos = new Vector3(x, 0, y) * spacing;
                Instantiate(prefab, pos, Quaternion.identity);
            }
        }
    }

Solution

  • OK, sorted the issue. As per my OP, I did have a baked Nav Mesh and prefabs had the Nav Mesh Agent component. The issue was the resolution of the Nav Mesh and the Base Offset on the Nav Mesh Agent which was set to -0.2.

    Rebaking the Nav Mesh with the Height Mesh setting made the walkable areas more accurate.

    enter image description here

    Together with changing the Base Offset on the Nav Mesh Agent to 0.

    enter image description here