IndexOutOfRangeException: Array index is out of range.

1k views Asked by At

IndexOutOfRangeException: Array index is out of range. WordScramble.ShowScramble (Int32 index, Int32 index2) (at Assets/Word Sramble/WordScramble.cs:210) WordScramble.Start () (at Assets/Word Sramble/WordScramble.cs:134)

public void ShowScramble(int index, int index2)
{
    textObjects.Clear ();
    charObjects.Clear ();
    foreach (Transform child in container) 
    {
        Destroy (child.gameObject);
    }


    //WORDS FINISHED
    //SHOW RESULT SCREEN
    if ((index > words.Length - 1) && (index2 > questions.Length - 1))
    {
        result.ShowResult();
        wordCanvas.SetActive(false);
        //Debug.Log ("index out of range, please enter range between 0-" + (words.Length - 1).ToString());
        return;
    }


    char[] chars = words [index].GetString ().ToCharArray ();
    char[] chars2 = questions [index2].GetString ().ToCharArray ();
    foreach (char c in chars) 
    {
        TextObject clone2 = Instantiate (prefabQstn.gameObject).GetComponent<TextObject> ();
        CharObject clone = Instantiate (prefab.gameObject).GetComponent<CharObject> ();

        clone.transform.SetParent (container);
        clone2.transform.SetParent (containerQstn);
        textObjects.Add (clone2.Init (c));
        charObjects.Add (clone.Init (c));

    }

    currentQstn = index2;
    currentWord = index;
    StartCoroutine (TimeLimit());
}
1

There are 1 answers

0
Marty On

The index check is not done properly. There needs to be an OR operation instead. Otherwise both indexes need to be out of range to satisfy the condition.

if ((index > words.Length - 1) || (index2 > questions.Length - 1))

It might be a good idea to include testing for negative numbers:

if ((index > words.Length - 1) || (index2 > questions.Length - 1) || index < 0 || index2 < 0)

Your not using the chars2 array in the following code, so consider maybe changing the code appropriately. But I guess it all depends on what you want the code to do.