- Home /
Question by
Ray_Adiiwiguna · Jan 09, 2020 at 06:11 PM ·
navmeshnavmeshagentpathfindingpointspatrol
How to stop at the last point so as not to return to the begining?
// Patrol.cs using UnityEngine; using UnityEngine.AI; using System.Collections;
public class Patrol : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint() {
// Returns if no points have been set up
if (points.Length == 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.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (!agent.pathPending && agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}
Comment
Answer by IINovaII · Jan 09, 2020 at 08:58 PM
You can do it by changing GotoNextPoint()
like this.
void GotoNextPoint()
{
if (points.Length == 0)
return;
if(destPoint < points.Length)
agent.destination = points[destPoint].position;
else
return;
destPoint++;
}
In this code, it will check if destPoint is less than points.Length. If it's true, then it will continue moving, otherwise it will stop. Whenever this function is called, destPoint's value is incremented by 1.