1

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();
    }
}

} This is the error

1 Answers1

0

I couldn't see which line the error was coming from but in Update the currentWP variable is being used without checking if it is a valid value (or if the path variable is valid). I'd recommend as a minimum adding a check in Update for that, something like:

if (path != null && currentWP >= 0 && currentWP < path.Count)
{
    // existing Update logic goes here
}

If that doesn't resolve it then grab a full copy of the error log from it. It will indicate the line number in the file and that'll help narrow it down.

I don't think this is causing the problem but worth noting that in FindClosestWP it looks like it always skips the first waypoint in the list? the index is starting at 1 rather than 0, is that intentional? The lastDist calculation there also seems to always refer back to the first point rather than the most recent one (ie. currentWP). I think this line:

float lastDist = Vector3.Distance(this.transform.position, path[0].position);

might need to be

float lastDist = Vector3.Distance(this.transform.position, path[currentWP].position);
Iain McManus
  • 1,095
  • 13
  • 21