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);
Thank you so much !
You are welcome 🙂 Glad you liked it.
You are most welcome!
You saved my day. Thank you!
thank you so much, i have been trying to solve this issue for weeks and finally it worked
I am glad that it helped 🙂 Thank you for getting back and letting me know that it worked.
Thank you!!! Rahmet)
You are most welcome 🙂
OMG!!! Thank you so much for this post!! I’ve been stuck for days on this issue.
I am really happy that this helped you 😀
OMG, this one was killing me. Thank you!
You are more than welcome 🙂 Thank you for telling me!
hey bro thanks a lot these two lines of code saved me a lot of trouble
Man, thanks for letting me know 🙂