Move Agent to Next Selected Target and Repeat Sequence.

Hi all,
I’m using the code below to move my agent to waypoints in a list.
Currently my agent moves to the first selected target and remains there.
What I’d like to do is modify this so my agent will move through the sequence of waypoints, repeating the selected target list infinitely.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AI_FindObjects : MonoBehaviour {
     public List <Transform> Waypoints;
     public Transform SelectedTarget;
     void Update ()
     {
         SelectedTarget = null;
         Enemies = new List<Transform>();
         AddWaypointsToList();
 
}
     public void AddWaypointsToList()
     {
         GameObject[] ItemsInList = GameObject.FindGameObjectsWithTag("Waypoint");
         foreach(GameObject _Enemy in ItemsInList)
         {
             AddTarget(_Waypoint.transform);
         }
     }
     public void AddTarget(Transform waypoint)
     {
         Waypoints.Add(waypoint);
     }
     public void DistanceToTarget()
     {
         Waypoints.Sort(delegate( Transform t1, Transform t2){
             return Vector3.Distance(t1.transform.position,transform.position).CompareTo(Vector3.Distance(t2.transform.position,transform.position));
         });
     }
     public void TargetedWaypoint()
     {
         if(SelectedTarget == null)
         {
             DistanceToTarget();
             SelectedTarget = Waypoints[0];
         }
     }
     void LateUpdate ()
     {
         TargetedWaypoint();
         float dist = Vector3.Distance(SelectedTarget.transform.position,transform.position);
          transform.position = Vector3.Lerp (transform.position, SelectedTarget.position, Time.deltaTime*1);
     }
}

For starters, you’re creating a whole new waypoints list every single frame at the bottom of Update, so that’s not good.

Instead, create a Queue in OnEnable(). When your script first starts, pop the first entry off the queue as your current target. When the agent is within an acceptable distance to the target, pop the next one off the queue and set that as the current target. Repeat until the queue is empty and then decide what’s next for your agent (Rebuild the queue? Stop for a while? Up to you).

1 Like

Thanks very much, GroZZleR!
Between your reply here and another post which you had assisted (from 6 years ago), I’m all set.
Appreciate your help across the years.

1 Like