(For regular readers, yes this blog is usually about my photography work, but I also program video games for fun! I’m going to be posting some stuff about my new game, and general programming stuff.)
One thing you commonly need to do when using Unity’s NavMesh pathfinding is to stop an agent, either permanently or just paused.
Unity has a function to do this: NavMeshAgent.Stop()
Unfortunately that doesn’t work. The agent just ignores it and carries on navigating the current path. It’s a bug that has existed for a few years now, so realistically we can’t wait for the Unity guys to fix it and we need to find a workaround ourselves.
Support forums suggest NavMeshAgent.ForgetPath() but that doesn’t work either.
The solution that people fall back on is to call NavMeshAgent.enabled = false but often that’s not what you want, because the agent is effectively removed from the simulation and won’t get bumped around by other agents making contact with it.
What’s the solution?
It’s simple, it’s stupid, and I’ve got no idea why it works but it does:
That’s it. You just set enabled to false and then immediately set it to true again. The agent will forget its current path, but continue to be part of the simulation.