我遇到错误IndexOutOfRangeException:数组索引超出范围

时间:2020-07-24 12:06:07

标签: c# arrays unity3d

我创建了一个场景,在该场景中我将演讲者和一些单词放在两个段落中,听完演讲者的播放器必须从段落1和段落2中识别单词。 我创建了两个大小分别为3的名称为answer1和answer2nd的数组,并将答案键存储在其中。我放置了条件以使当前所选游戏对象的名称与数组元素的名称匹配。 如果两个GameObjects具有相同的名称,则显示成功,否则将失败。在if if else结构中,我递增一个整数变量,该变量将对数组的所有三个元素进行求值。 当它测试第一个答案数组的最后一个元素时,它显示错误数组索引超出范围。我尝试了其他解决方案来解决,但无法解决。谁能帮我解决错误。 脚本粘贴在下面:

[SerializeField] GameObject[] answer;
[SerializeField] GameObject[] answer2nd;
[SerializeField] AudioClip[] guessWordSound;
GameObject currentObj;
[SerializeField] GameObject correct;
[SerializeField] GameObject wrong;
[SerializeField] AudioClip positiveSound;
[SerializeField] AudioClip negativeSound;
string objNname;
int soundIndex = 0;
int i=0 , a=0; 

public void PlaySound()
    {
        AudioSource.PlayClipAtPoint(guessWordSound[soundIndex], Vector3.zero, 0.8f);
        soundIndex++;
    }

public void submitans(string ans)
    {
        currentObj = EventSystem.current.currentSelectedGameObject;
        objNname = currentObj.name;

     if (objNname == answer[i].name)
        {
            correct.SetActive(true);
            wrong.SetActive(false);
            AudioSource.PlayClipAtPoint(positiveSound, Vector3.zero, 0.6f);
            i++;
        }
     else if(objNname == answer2nd[a].name)
        {
            correct.SetActive(true);
            wrong.SetActive(false);
            AudioSource.PlayClipAtPoint(positiveSound, Vector3.zero, 0.6f);
            a++;
          }
      else if (objNname != answer[i].name )
         {
            wrong.SetActive(true);
            correct.SetActive(false);
            AudioSource.PlayClipAtPoint(negativeSound, Vector3.zero, 0.6f);
           
           }
      else if(objNname != answer2nd[a].name)
       {
          wrong.SetActive(true);
          correct.SetActive(false);
          AudioSource.PlayClipAtPoint(negativeSound, Vector3.zero, 0.6f);

        }

}

0 个答案:

没有答案