NavMeshAgent.Warp

So, I have been having this problem, that after spawning my agents into the scene, all sort of strange behaviour started to happen. They would not be able to find a destination, or they would jump to a different location right after they had been instantiated. A typical error code from the console would be this.

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.

And then the agent would not move at all. But, the strange thing was that if I disabled and then re-enabled the NavMeshAgent – everything would start working as intended.

After a looking for some answers around the internet. I finally found the answer to this problem.

When instantiating a new GameObject, that happens to be a NavMeshAgent, the placing of the Object by transform.position will “confuse” the NavMeshAgent, and it will not have any connection to the navmesh at all. Instead of placing the GameObject by position, you have to use NavMeshAgent.Warp. This will let unity link the navmeshagent and the navmesh, and everything will be fine again 🙂

Here is a piece of example code that solved the problems for me:

GameObject newSoldier = Instantiate(soldiers[soldierLevel]) as GameObject;
newSoldier.GetComponent<UnityEngine.AI.NavMeshAgent> ().Warp (spawn.position);

Leave a Reply

Your email address will not be published. Required fields are marked *