As per title, the method FindPath looks for the GameObjects with the tag “Path” but it doesn’t place it into the list in order. As a result, the Ram goes all over the place attempting to follow the waypoint in the wrong order.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMover : MonoBehaviour
{
[SerializeField] List<Waypoint> path = new List<Waypoint>();
[SerializeField] [Range(0f, 5f)]float moveSpeed = 1f;
// Start is called before the first frame update
void Start()
{
FindPath();
StartCoroutine(FollowPath());
}
void FindPath()
{
path.Clear();
GameObject[] waypoints = GameObject.FindGameObjectsWithTag("Path");
foreach(GameObject waypoint in waypoints)
{
path.Add(waypoint.GetComponent<Waypoint>());
}
}
IEnumerator FollowPath()
{
foreach(Waypoint waypoint in path)
{
Vector3 startPosition = transform.position;
Vector3 endPosition = waypoint.transform.position;
float travelPercent = 0f;
transform.LookAt(endPosition);
while(travelPercent < 1f)
{
travelPercent += Time.deltaTime * moveSpeed;
transform.position = Vector3.Lerp(startPosition, endPosition, travelPercent);
yield return new WaitForEndOfFrame();
}
}
}
}