How to do it...

We will create a patrol behavior component to be used along with a NavMeshAgent component:

  1. 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
}
  1. Add the member variables required:
public float pointDistance = 0.5f;
public Transform[] patrolPoints;
private int currentPoint = 0;
private NavMeshAgent agent;
  1. Create a function for finding the closest patrol point in the array:
private int FindClosestPoint()
{
// next step
}
  1. Add the internal variables required:
int index = -1;
float distance = Mathf.Infinity;
int i;
Vector3 agentPosition = transform.position;
Vector3 pointPosition;
  1. 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;
  1. 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;
}
  1. Implement the Start function for initialization:
private void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.autoBraking = false;
currentPoint = FindClosestPoint();
GoToPoint(currentPoint);
}
  1. Implement the Update function:
private void Update()
{
if (!agent.pathPending && agent.remainingDistance < pointDistance)
GoToPoint((currentPoint + 1) % patrolPoints.Length);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.231.97