"Index was out of range." Error

My code is working as intended, but I’m getting this error in the console. How do I fix it without altering the code too heavily?

public class PawnEnemyManager : MonoBehaviour
{

    public List<GameObject> enemyList = new List<GameObject>();

    public UnitBehavior unitBehavior;


    // Update is called once per frame
    void Update()
    {
        if(enemyList[0] == null)
        {
            enemyList.Remove(enemyList[0]);
        }
       
        if(enemyList[0] != null)
        {
            unitBehavior.enemyTarget = enemyList[0].transform;
        }
    }

    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Enemy"))
        {
            enemyList.Add(other.gameObject);
        }
    }

    public void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Enemy"))
        {
            enemyList.Remove(other.gameObject);
            unitBehavior.enemyTarget = null;
        }
    }

}

In line 12 and line 17 above in your Update function you unconditionally dereference the 0th element. If that list is empty, you will get the given error.

You can check how many items are in the array with the .Count property, see if it is greater than zero for example.

There will be times where the list will have nothing on it. The list is used to keep track of how many enemies are within “sight” of the player.

So when the first enemy on the list is beyond the Trigger or it dies (destroyed). It needs to check and make sure enemyList[0] is not a missing object and remove it, so the player can assign the next enemy in the list. If there is one.

Exactly. And that is why you want to check if there is anything in it before assuming there is, as your original code assumes.

Oh, I just figured out what you were advising me to do. Thank you!

1 Like