2017-09-09 13 views
0

IndexOutOfRangeException:配列インデックスが範囲外です。 WordScramble.ShowScramble(のInt32インデックス、のInt32 INDEX2):(資産/ワードSramble/WordScramble.cs時:134)(資産/ワードSramble/WordScramble.csにおける210) WordScramble.Start()IndexOutOfRangeException:配列インデックスが範囲外です。

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()); 
} 
+0

コード/例外メッセージをダンプする代わりに問題を説明してください – Sybren

+0

'(index> words.Length - 1)&&(index2> questions.Length - 1)'の条件は**両方のインデックス**がそれぞれの長さよりも大きいので、配列に無効なインデックスを渡すことは明らかです。 –

答えて

1

索引検査が正しく行われていません。代わりにOR演算が必要です。それ以外の場合は、条件を満たすために両方のインデックスが範囲外である必要があります。

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

負の数のテストを含めることは良い考えかもしれません:

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

あなたは、次のコードでchars2アレイを使用していない、ので、多分適切にコードを変更することを検討してください。しかし、私はそれがすべてあなたがコードが欲しいものに依存していると思います。

関連する問題