I can make a simple waypoints script that move a transform between the waypoints and I can make a navmeshagent to move between the waypoints. It seems like navmeshagent have everything needed for waypoints system. But in many cases I see very long and many scripts with path finding and math and complicated scripts for waypoints.
Why not just using navmeshagent all the time ? In what cases should I use navmeshagent ? navmeshagent is only for kind of patrolling ?
I have a simple waypoints script: I turned the autobraking on set it to true since I want the agents to slow down when getting close to the waypoint/s:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AgentControl : MonoBehaviour
{
public List<Transform> points = new List<Transform>();
private int destPoint = 0;
private NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
var agentsDestionations = GameObject.FindGameObjectsWithTag("Waypoint");
for (int i = 0; i < agentsDestionations.Length; i++)
{
points.Add(agentsDestionations[i].transform);
}
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = true;
agent.speed = Random.Range(10, 50);
GotoNextPoint();
}
void GotoNextPoint()
{
// Returns if no points have been set up
if (points.Count == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Count;
}
void Update()
{
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}
I didn’t change any other properties on the NavMeshAgent but the autobraking.
For testing I tried with 500 agents and 500 waypoints or 10 agents and 10 waypoints in both cases some of the agents get stuck/staying on a waypoint and not moving to the next waypoint/s. I can’t figure out why.
The red are the agents the blue are the waypoints.
The close 4 agents stay on the blue waypoint while the other agents keep moving between the waypoints.
So I have two wonders: When and why to use navmeshagent in waypoints ? And why some of them stop at a waypoint and not continue ?