(SOLVED) How can I prevent " index was out of range" error on this script?

I’m trying to find a way to prevent an “index was out of range” error in update when there aren’t any targets to find.
I thought I could add an if statement to return if there weren’t any “selected objects,” but I’m still encountering the error.

 using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AI_FindObjects : MonoBehaviour {

     public List <Transform> Enemies;
     public Transform SelectedTarget;
 
     void Update ()
     {

         SelectedTarget = null;
         Enemies = new List<Transform>();
         AddEnemiesToList();
     
}
     public void AddEnemiesToList()
     {
         GameObject[] ItemsInList = GameObject.FindGameObjectsWithTag("PitcherPlant");
         foreach(GameObject _Enemy in ItemsInList)
         {
             AddTarget(_Enemy.transform);
         }
     }
     public void AddTarget(Transform enemy)
     {
         Enemies.Add(enemy);
     }
     public void DistanceToTarget()
     {
         Enemies.Sort(delegate( Transform t1, Transform t2){
             return Vector3.Distance(t1.transform.position,transform.position).CompareTo(Vector3.Distance(t2.transform.position,transform.position));
         });
     }
     public void TargetedEnemy()
     {
         if(SelectedTarget == null)
         {
             DistanceToTarget();
             SelectedTarget = Enemies[0];
         }
     }
     void LateUpdate ()
     {
         TargetedEnemy();
         float dist = Vector3.Distance(SelectedTarget.transform.position,transform.position);
          transform.position = Vector3.Lerp (transform.position, SelectedTarget.position, Time.deltaTime*1);
     }
}

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

First, find where the out of range is happening.

Second, find why

Third, fix that.

Thanks, Kurt,
I found where the error is coming from- which is the “Enemies” in the above list.
And the why- there aren’t any “Enemies” in the scene at runtime.
What I’m not understanding is how to check if there are no Enemies, and prevent this exception error.

The only dereference I see is line 40 above… you are hard-wiring and grabbing the first one (element zero).

Don’t do that if there isn’t anything in the list. Collections such a list have a .Count property you can check to make sure it’s greater than zero, and Arrays use the .Length property instead.

Something you can do to improve your script (as you’re creating a new List every frame) is clear it instead:

  • Change line 6 to: public List<Transform> Enemies = new List<Transform>();
  • Change line 13 to: Enemies.Clear();

And as Kurt mentioned, you can dodge the error in line 40 by changing line 37 to…
if ((SelectedTarget == null) && (Enemies.Count != 0))
…and after line 45, you should add…
if (SelectedTarget == null) return;

1 Like

Thanks, Polemical- that sorted the issue out, grateful for the help.
Also, thanks for showing me the reason behind this error, Kurt- much appreciated!

2 Likes