Hello, I’m really new to Unity and am working on making my first game for a project for a school club. I am working on designing a 2D board game with dice mechanics. However, whenever I try to run my game I get this error message. IndexOutOfRangeException: Index was outside the bounds of the array.
Dice.Start () (at Assets/Scripts/Dice.cs:15). Due to me being very new I’m not exactly sure how to fix this problem. I am using a script made by somebody else and following their tutorial. I would really appreciate some help with this issue. Thank you! Below I have attached an image of my code if that helps.
IndexOutOfRangeException: Index was outside the bounds of the array. Error Message. Cannot find fix.
diceSides
is an array of Sprites. An array is an object that can store a set number of elements, in this case, a set number of Sprites.
An IndexOutOfRangeException
is thrown when you try to access an element at an index that is either less than 0 or greater than the set number of elements the array can hold.
So on line 15, you’re trying to access the 5th index element in the array, but that index is greater than the total size of the array, thus, throwing the exception.
You can use the array.Length
property to check the size of the array. Try printing out that value just before line 15 to see what it is:
Debug.Log(diceSides.Length);
See: C# - Arrays
I’m not too sure about following this tutorial though, since it’s using Resources.Load
here to assign the references in the array for seemingly no real reason? There are other (and frankly, better) ways of assigning the Sprites to the array. Resources.Load
has its use-cases, but I don’t see why it would be used here instead of dragging/dropping the Sprites in the inspector like one typically would.
If diceSides.Length
is printing 0 in the console, then you don’t have any Sprite assets in your “Resources/DiceSides/” directory, which is how the script is trying to assign them to the array, but again, there really shouldn’t be a need to use Resources.Load
here.
Everything @Vryken said above… PERFECT.
Here are some more notes on IndexOutOfRangeException and ArgumentOutOfRangeException: