Index was out of range. Must be non-negative and less than the size of the collection.

Good day everyone. I’m still fairly new to unity, and as my first game I have been working on creating a visual memory card game.

I wanted to implement a restart button in my game that would reset the score count, however whenever I try to click on something in the scene that is NOT a card, I’m faced with an error, and I’m not sure what exactly is wrong with my code.

This is the part of my code in which I’m getting the error at:

    void OnMouseDown()
    {
        int originalLength = frontIndexes.Count;
        float yPosition = 2.3f;
        float xPosition = -2.2f;

        if (spriteRenderer.sprite == board)
        {

            //creating this for loop in order to generate more clones of the card
            for (int i = 0; i < 7; i++)
            {
                shuffleNumber = random.Next(0, frontIndexes.Count);
                Debug.Log(shuffleNumber);
                var temp = Instantiate(token, new Vector3(xPosition, yPosition, 0f),
                            Quaternion.identity);

                temp.GetComponent<FlippingCard>().frontIndex = frontIndexes[shuffleNumber];
                frontIndexes.Remove(frontIndexes[shuffleNumber]);

                xPosition = xPosition + 4;
                if (i == (originalLength/2 - 2))
                {
                    yPosition = -2.3f;
                    xPosition = -6.2f;
                }

            }
            token.GetComponent<FlippingCard>().frontIndex = frontIndexes[0];
        }
    }

The error I get is on line 36, where it says: temp.GetComponent<FlippingCard>().frontIndex = frontIndexes[shuffleNumber];

Error:

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at <9577ac7a62ef43179789031239ba8798>:0)
System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <9577ac7a62ef43179789031239ba8798>:0)
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <9577ac7a62ef43179789031239ba8798>:0)
MakeVisible.OnMouseDown () (at Assets/Scripts/MakeVisible.cs:36)

I’ve been trying to find a solution for this for the past 2 hours and I’m starting to get a headache. :smiley:

(This is also the first ever question I’m publishing here so I’m very sorry if the formatting of my question seems odd).

I am thinking that shuffleNumber = random.Next(0, frontIndexes.Count); might eval 0 when there are no more frontIndexes, so that when you later access frontIndexes[shuffleNumber] you are trying to get the first item from an empty list. Check if you are removing too many items (change from 7 to 6?) or break out of the loop if frontIndexes.Count == 0