0

I was creating a Quiz game on Unity and this ArgumentOutOfRangeException keeps on showing and I can't start the game since I'm a beginner can you guys help me. These 3 Lines of code are the reasons idk how to fix it

private void SelectQuestion()
{
    int val = UnityEngine.Random.Range(0, questions.Count);
    selectedQuestion = questions[val];

    quizUI.SetQuestion(selectedQuestion);

    questions.RemoveAt(val);
}

public void StartGame(int index)
{
    scoreCount = 0;
    currentTime = timeLimit;
    lifeRemaining = 3;

    questions = quizData[index].questions;
    

    SelectQuestion();
    gameStatus = GameStatus.Playing;
}

private void Start()
{
    for(int i = 0; i < options.Count; i++)
    {
        Button localBtn = options[i];
        localBtn.onClick.AddListener(() => OnClick(localBtn));
    }

    for (int i = 0; i < uiButtons.Count; i++)
    {
        Button localBtn = uiButtons[i];
        localBtn.onClick.AddListener(() => OnClick(localBtn));
    }

 
}
Yssa27
  • 9
  • 3

1 Answers1

0
int val = UnityEngine.Random.Range(0, questions.Count);

Change this to

int val = UnityEngine.Random.Range(0, questions.Count -1);

This should work. Always remember, never do Array[Array.Length] or Array[List.Count]. C# is 0 indexed!

int[] arr = {1,2,3,4};
Console.WriteLine(arr.Length);

the above example returns 4, not 3(which is the maximum array index). Hope this helped!

jkimishere
  • 127
  • 1
  • 7