using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; // import Linq library public class WaypointController: MonoBehaviour { [SerializeField] private Transform[] waypoints = null; // a list of waypoints for the NPC to wander around [SerializeField] private bool randomPatrol = false; // indicates if agent should randomly patrol the waypoints [SerializeField] private float stoppingDistance = 0.5f; // Create a public read-only property StoppingDistance to return the Stopping Distance public float StoppingDistance { get { return stoppingDistance; } } private int numberWaypoints = 0; private List visitedWaypoints; // stores the index number of visited waypoints private void Awake() { // Get the number of specified waypoints for the AI to wander around numberWaypoints = waypoints.Length; // Initialise the visted waypoint to a new blank list ready to receive waypoints visitedWaypoints = new List(); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public Transform GetNextWaypoint() { // if no waypoints have been specified, no need to continue, return null and exit the method early if (numberWaypoints == 0) return null; // If all waypoints have been visited remove all but the current (last) waypoint if (visitedWaypoints.Count == numberWaypoints) visitedWaypoints.RemoveRange(0, numberWaypoints - 1); // Declare variable to store next index number int nextIndex = 0; // Check if AI is randomly patrolling the waypoints if (randomPatrol) { // Get a random waypoint index nextIndex = Random.Range(0, numberWaypoints); // Check if the random index generated NOT the random index number of an already visited waypoint // If yes, keep trying to generate till you get one not visited in this cycle while (visitedWaypoints.Contains(nextIndex)) // randomIndex == currentWaypointIndex || is the current waypoint's index number OR { nextIndex = Random.Range(0, numberWaypoints); } } // Else if not randomly patrolling, get the next index number. // Remember if no waypoints have been visted OR you have visited all waypoints, you will need to start back at zero else { if (visitedWaypoints.Count > 0 && visitedWaypoints.Last() < numberWaypoints - 1) { nextIndex = visitedWaypoints.Last() + 1; } } //Debug.Log(nextIndex); // Add the selected waypoint to visit to the list of visited waypoints visitedWaypoints.Add(nextIndex); // Return the next waypoint return waypoints[nextIndex]; } }