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 ...

Get Unity 2018 Artificial Intelligence Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.