Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

"Index was out of range." Error

Discussion in 'Scripting' started by Cohav0310, Aug 30, 2019.

  1. Cohav0310

    Cohav0310

    Joined:
    Aug 11, 2018
    Posts:
    9
    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?

    Code (CSharp):
    1. public class PawnEnemyManager : MonoBehaviour
    2. {
    3.  
    4.     public List<GameObject> enemyList = new List<GameObject>();
    5.  
    6.     public UnitBehavior unitBehavior;
    7.  
    8.  
    9.     // Update is called once per frame
    10.     void Update()
    11.     {
    12.         if(enemyList[0] == null)
    13.         {
    14.             enemyList.Remove(enemyList[0]);
    15.         }
    16.        
    17.         if(enemyList[0] != null)
    18.         {
    19.             unitBehavior.enemyTarget = enemyList[0].transform;
    20.         }
    21.     }
    22.  
    23.     public void OnTriggerEnter2D(Collider2D other)
    24.     {
    25.         if (other.gameObject.CompareTag("Enemy"))
    26.         {
    27.             enemyList.Add(other.gameObject);
    28.         }
    29.     }
    30.  
    31.     public void OnTriggerExit2D(Collider2D other)
    32.     {
    33.         if (other.gameObject.CompareTag("Enemy"))
    34.         {
    35.             enemyList.Remove(other.gameObject);
    36.             unitBehavior.enemyTarget = null;
    37.         }
    38.     }
    39.  
    40. }
    41.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    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.
     
  3. Cohav0310

    Cohav0310

    Joined:
    Aug 11, 2018
    Posts:
    9
    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.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    Exactly. And that is why you want to check if there is anything in it before assuming there is, as your original code assumes.
     
  5. Cohav0310

    Cohav0310

    Joined:
    Aug 11, 2018
    Posts:
    9
    Oh, I just figured out what you were advising me to do. Thank you!
     
    Kurt-Dekker likes this.