Out of range exception

When I run this part of the script it always gives the error:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Every time I run this it always spits out the error. I can’t find any way to make it not show the error.

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

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

public void Display()
{
    Hide();
    PickHand();
    ShowHand();
}

void ShowHand()
{
    foreach (GameObject card in hand)
    {
        card.SetActive(true);
    }
}

void PickHand()
{
    for (int i = 0; i < 5; i++)
    {
        GameObject card = deck[Random.Range(0, deck.Count)];
        deck.Remove(card);
        hand.Add(card);
    }
}

void Hide()
{
    foreach (GameObject card in deck)
    {
        card.SetActive(false);
    }
}

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 that a collection with ZERO elements cannot be indexed at all: it is empty
  • remember you might have more than one instance of this script in your scene/prefab
  • remember the collection may be used in more than one location in the code
  • remember that 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.

1 Like

It’s helpful to include the stack trace for the exception, so you can tell us which exact line the error occurs on in the code you posted. With that said. PickHand will throw an exception doing deck[Random.Range(0, deck.Count)] when deck is empty. Think about how you want your code to behave when there is nothing left in deck.

1 Like

Thanks I figured out the problem.