- Home /
How to Calculate NavMeshAgent Paths Quicker
I'm trying to see how many NavMeshAgents Unity can handle, and something that's really holding me back is the time unity takes to calculate the paths of thousands of agents.
I move my Agents in a big rectangle centered around whatever point I feed in. I don't let the rectangle of agents move until all of them have found their paths, and this means that after I give them a position they can take seconds before they move depending on how far the path is. I don't give them any real obstacles either, so the paths should be straight forward.
I feed in the paths very simply:
if(numOfSoldiers % rows == 0)
{
Vector3 startPoint = new Vector3(targetPos.x - (numOfSoldiers / rows / 2) * soldierDist, targetPos.y, targetPos.z + soldierDist);
for (int x = 0; x < rows; x++)
{
for (int y = 0; y < numOfSoldiers / rows; y++)
{
//Stop soldier movement until all paths are calculated(see Update())
soldiers[y + (x * (numOfSoldiers / rows))].GetComponent<NavMeshAgent>().isStopped = true;
stopped = true;
soldiers[y + (x * (numOfSoldiers / rows))].GetComponent<NavMeshAgent>().SetDestination(startPoint + new Vector3(soldierDist * y + Random.Range(-randomDist, randomDist), 0, -soldierDist * x + Random.Range(-randomDist, randomDist)));
}
}
}
and I start their movement again just as simply:
//If calculating paths
if(stopped == true)
{
bool pending = false;
foreach (GameObject soldier in soldiers)
{
//If a soldier is calculating paths, do nothing
if(soldier.GetComponent<NavMeshAgent>().pathPending == true)
{
pending = true;
break;
}
}
//else, move the regiment
if(pending == false)
{
stopped = false;
foreach (GameObject soldier in soldiers)
{
soldier.GetComponent<NavMeshAgent>().isStopped = false;
}
}
}
My framerate is still perfect, it's simply the calculations that take a long time. Is there anyway to do these calculations quicker, or maybe simultaneously? Even if it's resource intensive, I'd like to know if there's anything I can do to move all of these quicker when they're moving to a similar place.
Answer by Temseii · Sep 01, 2021 at 08:59 AM
I'd recommend just using Aron Granberg's pathfinding package, it's a lot more performant than Unity's and allows for multithreaded operations.