List OutOfRange Error

I’m currently running into an issue with a script that keeps track of characters nearby my player character by using a Collider and a List, but when I’m trying to get character data from the list, it gives me an OutOfRange error. In the editor, the list is populating, but when trying to access through the script, it just gives me the error. I’ve tried setting the List to static and checked the editor for other instances of the object, but I cannot find any additional versions of this script.

    //Sending selection
    public GameObject makeSelection()
    {
        //Cleaning up
        Destroy(selector);

        //If making a selection, menu style
        if (ActivelySelecting)
        {
            ActivelySelecting = false;
            return CharacterSelections[Index];
        }

        //If moving around and need to select a character
        Debug.Log("Passive List: " + PassiveSelections.Count);
        if (PassivelySelecting)
        {
            PassivelySelecting = false;
            return PassiveSelections[Index];    //Index should be 0 [Error Here]
        }

        Debug.Log("Error in making a selection.");
        return null;
    }

    //When Ally/Enemy enters activation area
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //if Avatar needs to be close to a character to select
        if (PassivelySelecting)
        {
            //Debug.Log("GameObject has Entered");
            //Determining which types of character should be added
            switch (CharactersToLookFor)
            {
                case "Ally":
                    if (collision.CompareTag("Ally"))
                    {
                        PassiveSelections.Add(collision.gameObject);
                        //PassiveSelections.TrimExcess();
                        if (PassiveSelections.Count == 1)
                            selector = Instantiate(SelectorIcon, PassiveSelections[0].transform.position, Quaternion.identity);

                        Debug.Log("Ally has entered radius.");
                    }
                    break;
                case "Enemy":
                    if (collision.CompareTag("Enemy"))
                    {
                        PassiveSelections.Add(collision.gameObject);
                        //PassiveSelections.TrimExcess();
                        if (PassiveSelections.Count == 1)
                            selector = Instantiate(SelectorIcon, PassiveSelections[0].transform.position, Quaternion.identity);

                        Debug.Log("Enemy has entered radius.");
                    }
                    break;
                case "Any":
                    if (collision.CompareTag("Ally") || collision.CompareTag("Enemy"))
                    {
                        PassiveSelections.Add(collision.gameObject);
                        //PassiveSelections.TrimExcess();
                        if (PassiveSelections.Count == 1)
                            selector = Instantiate(SelectorIcon, PassiveSelections[0].transform.position, Quaternion.identity);

                        Debug.Log("Character has entered radius.");
                    }
                    break;
                default:
                    Debug.Log("Error: Incorrect Selection Type String was Passed.");
                    break;
            }
        }
    }

    //When Ally/Enemy exits activation area
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (PassivelySelecting)
        {
            //Removing character from list
            PassiveSelections.Remove(collision.gameObject);
            PassiveSelections.TrimExcess();

            //checking if another character should be selected
            if (PassiveSelections.Count > 0)
                selector.transform.position = PassiveSelections[0].transform.position;
            else
                Destroy(selector);

            Debug.Log(collision.tag + " has exited radius.");
        }
    }

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

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

Steps to success:

  • find which collection it is and what line of code accesses it <— (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection size

Remember also:

  • a collection with ZERO elements cannot be indexed at all: it is empty
  • you might have more than one instance of this script in your scene/prefab
  • the collection may be used in more than one location in the code
  • indices start at ZERO (0) and go to the count / length minus 1.

This means with three (3) elements in your collection, they are numbered 0, 1, and 2 only.

from a quick glance at the code your issue is not clear.

in general “count” will give the number of items but to find the index of the last element you need to substract 1 from the total count amount. this is important if you do any type of for loop.

this is because in you code is not clear where you set that index variable

but regardless, before starting coding these complex gameplay interactions with a lot of if else a good idea would be to look into coding patterns especially those for games.

instead of checking who got out of range and then you put it in a list and then remove it and whatever, if this is not something that is super essential and important for your game concept, maybe you could implement a pattern. and remember you can use more of them for different parts of gameplay logic

https://gameprogrammingpatterns.com/contents.html

I looked through the scripts that called the makeSelection() function and found one that cleared the List before trying to access it. Thank you very much for pointing out to look around to make sure that I checked the index/Count related bits of code.