Good day everyone. I’m still fairly new to unity and C#, and as my very 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 (e.g the game board or the restart button), 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:
public Sprite board;
public GameObject token;
List<int> frontIndexes = new List<int>() { 0, 1, 2, 3, 0, 1, 2, 3 };
public static System.Random random = new System.Random();
public int shuffleNumber;
int[] visibleFaces = { -1, -2 };
SpriteRenderer spriteRenderer;
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
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 this line, 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 fix it but I was unable to come up with a solution. I’d really appreciate the help!