We will create a patrol behavior component to be used along with a NavMeshAgent component:
- Create a script named NMPatrol.cs, and include the NavMeshAgent as a required component:
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class NMPatrol : MonoBehaviour
{
// next steps
}
- Add the member variables required:
public float pointDistance = 0.5f;
public Transform[] patrolPoints;
private int currentPoint = 0;
private NavMeshAgent agent;
- Create a function for finding the closest patrol point in the array:
private int FindClosestPoint()
{
// next step
}
- Add the internal variables required:
int index = -1;
float distance = Mathf.Infinity;
int i;
Vector3 agentPosition = transform.position;
Vector3 pointPosition;
- Implement the loop for finding the closest point:
for (i = 0; i < patrolPoints.Length; i++)
{
pointPosition = patrolPoints[i].position;
float d = Vector3.Distance(agentPosition, pointPosition);
if (d < distance)
{
index = i;
distance = d;
}
}
return index;
- Implement the function for updating the agent's destination point:
private void GoToPoint(int next)
{
if (next < 0 || next >= patrolPoints.Length)
return;
agent.destination = patrolPoints[next].position;
}
- Implement the Start function for initialization:
private void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.autoBraking = false;
currentPoint = FindClosestPoint();
GoToPoint(currentPoint);
}
- Implement the Update function:
private void Update()
{
if (!agent.pathPending && agent.remainingDistance < pointDistance)
GoToPoint((currentPoint + 1) % patrolPoints.Length);
}