Getting index out of bound error even though it isn't

I am getting this error:
IndexOutOfRangeException: Index was outside the bounds of the array.
GenerateDice.Roll () (at Assets/scripts/GenerateDice.cs:64)

I do not understand why I am getting that error. If the element at choices[0] is 1 for example, it gives me an out of bounds error even though textboxes[ ] is size 6.

choices is a string, which means choices* is a char; i.e. a letter. In C#, a char is a 16-bit number that expresses a unicode code point in utf-16 format.*
When you try to use that char as an array index, it is implicitly converted from a char to an int. This implicit conversion preserves the numerical value of the code point. For example, a character of β€˜1’ is represented by the numerical value 49.
(This might seem byzantine, but think about what would happen if the character you tried to convert were β€˜a’ or β€˜=’ or β€˜Β’β€™ rather than being a digit.)
If you want to reinterpret a string as a number in the way that a human would read it when seeing it as text, you should generally use something like int.TryParse. (Although in the special case where you know that it’s a single character in the range of β€˜0’ to β€˜9’, you could also cast it to an integer and subtract 48. This is simpler and faster, but more brittle.)

2 Likes

so the code would look something like this?

textbox[(int)Char.GetNumericValue('choice[i]')]

Int32.TryParse will tell you if there’s number in your string and return that number if it is there

If you remove the quotes, then I believe that will work. (Keeping in mind that if the character isn’t a digit, GetNumericValue will return -1 and cause an array-out-of-bounds exception.)