Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

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

Discussion in 'Scripting' started by frankienglish0416, Nov 26, 2019.

  1. frankienglish0416

    frankienglish0416

    Joined:
    Nov 25, 2019
    Posts:
    7
    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.
     
    Last edited: Dec 2, 2019
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    choices
    is a string, which means
    choices[i]
    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.)
     
  3. frankienglish0416

    frankienglish0416

    Joined:
    Nov 25, 2019
    Posts:
    7
    so the code would look something like this?

    Code (CSharp):
    1. textbox[(int)Char.GetNumericValue('choice[i]')]
     
  4. frankienglish0416

    frankienglish0416

    Joined:
    Nov 25, 2019
    Posts:
    7
    so the code would look something like this?
    Code (CSharp):
    1. textbox[(int)Char.GetNumericValue('choice[i]')]
     
  5. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    Int32.TryParse will tell you if there's number in your string and return that number if it is there
     
  6. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    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.)