- Home /
How to redirect a navmesh agent's path based on area costs?
Hey everyone, I'm trying to create robust crowd movement of AI agents, such that if a pathway towards a goal gets too clogged with agents, other agents will know to find a more time-efficient path. Right now, each agent's destination is the same "goal" GameObject and they chose the shortest path towards this goal.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Agent : MonoBehaviour
{
public Transform goal;
void Update()
{
transform.GetComponent<UnityEngine.AI.NavMeshAgent>().destination = goal.position;
}
}
I've also set up a grid of triggers. Each trigger counts how many agents are in it and assigns this number to the area cost of that trigger.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class DensityCount : MonoBehaviour
{
public List<GameObject> agentList = new List<GameObject>();
void Update()
{
NavMesh.SetAreaCost(NavMesh.GetAreaFromName(transform.name), agentList.Count);
if (agentList.Count <= 0)
{
NavMesh.SetAreaCost(NavMesh.GetAreaFromName(transform.name), 1);
}
}
private void OnTriggerEnter(Collider other)
{
if (!agentList.Contains(other.gameObject)) // if object is not in list
{
agentList.Add(other.gameObject);
}
}
private void OnTriggerExit(Collider other)
{
if (agentList.Contains(other.gameObject)) // if object is in list
{
agentList.Remove(other.gameObject);
}
}
}
What I'm not sure how to do is make the agents redirect their path based on the area cost of the area they are in. So if an area cost is high, the agents will avoid that area and try to find a quicker path to the goal. In my demo, the red cylinders are the agents and the green cylinder is the goal they move towards. Any help is appreciated.
Your answer
Follow this Question
Related Questions
Why navmesh area cost is not changing agent's path? 0 Answers
NavMeshAgent following road (even if slightly longer path) 1 Answer
Making NavMesh areas? 0 Answers
Randomize NavMeshAgents path finding with same destination 1 Answer
Is it possible to store NavMeshAgents paths and assign them to other NavMeshAgents later? 1 Answer