Advertisement
LeeMace

Enemy Patrol with NavMesh

Oct 3rd, 2023
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | Gaming | 0 0
  1. //PatrolRoute gameobject and children locations have been created
  2. // enemy has a navmeshagent component on it.
  3.  
  4. using UnityEngine.AI;
  5.  
  6. public class EnemyBehaviour : MonoBehaviour
  7. {
  8.  
  9.     [SerializeField] private Transform patrolRoute;
  10.     [SerializeField] private List<Transform> locations;
  11.     private int locationIndex = 0;
  12.     private NavMeshAgent agent;
  13.  
  14.  
  15.     private void Start() {
  16.  
  17.         agent = GetComponent<NavMeshAgent>();
  18.         InitializePatrolRoute();
  19.         MoveToNextPatrolLocation();
  20.     }
  21.  
  22.     private void Update() {
  23.        
  24.         if (agent.remainingDistance< 0.2f && !agent.pathPending) {
  25.  
  26.             MoveToNextPatrolLocation();
  27.         }
  28.     }
  29.     private void MoveToNextPatrolLocation() {
  30.  
  31.         if (locations.Count == 0) { return; }
  32.         agent.destination = locations[locationIndex].position;
  33.         locationIndex = (locationIndex + 1) % locations.Count;
  34.     }
  35.  
  36.     private void InitializePatrolRoute() {
  37.  
  38.         foreach (Transform child in patrolRoute)
  39.         {
  40.             locations.Add(child);
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement