Hello I am new to c# and unity anyone know how to fix argument out of range exception that happens on this code im working on. This code is used for finding closest waypoint AI, i've tried changing the integer but to no avail.Thank you for taking your time reading this.
public class FindClosest : MonoBehaviour
{
public GameObject[] waypoints;
Animator anim;
public float rotspeed = 0.8f;
public float speed = 3f;
float accuracyWP = 2.0f;
int currentWP = 0;
List<Transform> path = new List<Transform>();
void Start()
{
anim = GetComponent<Animator>();
foreach (GameObject go in waypoints)
{
path.Add(go.transform);
}
currentWP = FindClosestWP();
anim.SetBool("isWalking", true);
}
int FindClosestWP()
{
if (path.Count == 0) return -1;
int closest = 0;
float lastDist = Vector3.Distance(this.transform.position, path[0].position);
for(int i = 1; i < path.Count; i++)
{
float thisDist = Vector3.Distance(this.transform.position, path[i].position);
if(lastDist > thisDist && i != currentWP)
{
closest = i;
}
}
return closest;
}
void Update()
{
Vector3 direction = path[currentWP].position - transform.position;
this.transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(direction), rotspeed * Time.deltaTime);
this.transform.Translate(0, 0, Time.deltaTime * speed);
if(direction.magnitude < accuracyWP)
{
path.Remove(path[currentWP]);
currentWP = FindClosestWP();
}
}