0

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());
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Please explain the problem instead of dumping the code / exception message – Sybren Sep 09 '17 at 09:52
  • The condition `(index > words.Length - 1) && (index2 > questions.Length - 1)` is true only if **both indexes** are greater than their respective lengths so obviously you can pass an invalid index to arrays. – Alessandro D'Andria Sep 09 '17 at 09:56
  • Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221) – Suraj Rao Feb 09 '21 at 14:46

1 Answers1

1

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.

Marty
  • 412
  • 3
  • 7