Search code examples
unity-game-engineagentnavmesh

Unity3D how to connect NavMesh and NavMeshAgent


I'm getting this error in the editor

"SetDestination" can only be called on an active agent that has been placed on a NavMesh. These are the steps that I tried when solving the problem:

  1. Warping NavmeshAgent to the NavMesh location
  2. Manually moving the NavMeshAgent to NavMesh
  3. Rebaking the NavMesh and doing the steps above
  4. Creating a box with NavMeshAgent and a new NavMesh
    • does anyone have any other tips that I could use?

Solution

  • Warping the Nav Mesh Agents position can sometimes cause errors, especially if it has gone from one navmesh to another.

    It's a strange bug, but it seems detecting if the agent is not on the navmesh, and then disabling and re-enabling the agent - will fix the issue (it did in my case).

    I've solved this in my project by doing the following when I warp.

    //use some existing reference to your NavMeshAgent
    NavMeshAgent agent = PlayerController.instance.GetComponent<NavMeshAgent>(); 
    
    //This will fire when you get the error you're describing.
    if (!agent.isOnNavMesh)
    {
       Vector3 warpPosition; //Set to position you want to warp to
       agent.transform.position = warpPosition;
       agent.enabled = false;
       agent.enabled = true;
    }