Many navmesh agents makes causes them to freeze/creates delay with input

I have navmesh agents that chase and others that flee. When I have more than 150-200 navmesh agents in my scene, they all seem to freeze for a moment before setting their new “fleeing destination”. Strangely, the game doesn’t lag at all, only the navmesh agents’ behavior does. It’s as if there were too many paths to compute and they just can’t deliver.

The way my system works, each agent has a big sphere collider which, from the point of view of a fleeing agent, stores the incoming pursuer into a list and then goes over each pursuer in this list (with a foreach loop) to determine which one is the closest and where to run in the opposite direction. The functions are called with InvokeRepeating(“Class”,0,0.5f).

It really bugs me because I’ve tried changing the whole system so that it uses coroutines primarily but that only accentuated the agent freezing (with visual game-wide lag this time).

The profiler and google haven’t been of much help either. I could really use a hand.

NavMesh.SetDestination is an asynchronous call but I don’t think it is multi threaded. So I am guessing if the core this is using gets maxed out then it throws stuff in a queue and “gets around to it” when there is time/CPU.

My fix was to replace NavMesh.SetDestination with NavMesh.CalculatePath. Create a new path, set your agent to the new path and update the path periodically with NavMesh.CalculatePath. This is not asynchronous and you might lose a little performance.

Now your agents will not stop when system is taxed. Also, you can rely on the path and time the agent takes to get to the destination being consistent. Thinking of “Tower Defence” games where this would be critical.