Another ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

hi everyone, im currently get stuck with this code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class QuestionSetup : MonoBehaviour
{
    [SerializeField]
    public List<QuestionData> questions;
    private QuestionData currentQuestion;

    [SerializeField]
    private TextMeshProUGUI questionText;
    [SerializeField]
    private TextMeshProUGUI categoryText;
    [SerializeField]
    private AnswerButton[] answerButtons;

    [SerializeField]
    private int correctAnswerChoice;

    private string selectedCategory;

    private void Awake()
    {
        // Get the selected category from PlayerPrefs
        selectedCategory = PlayerPrefs.GetString("SelectedCategory", "Umum");

        // Get all the questions ready
        GetQuestionAssets();
    }

    // Start is called before the first frame update
    public void Start()
    {
        // Filter questions based on the selected category
        FilterQuestionsByCategory();

        // Get a new question
        SelectNewQuestion();

        // Set all text and values on screen
        SetQuestionValues();

        // Set all of the answer buttons text and correct answer values
        SetAnswerValues();
    }

    private void FilterQuestionsByCategory()
    {
        questions = questions.FindAll(question => question.category == selectedCategory);
    }

    public void GetQuestionAssets()
    {
        // Get all of the questions from the questions folder
        questions = new List<QuestionData>(Resources.LoadAll<QuestionData>("Pertanyaan"));
    }

    private void SelectNewQuestion()
    {
        // Get a random value for which question to choose
        int randomQuestionIndex = Random.Range(0, questions.Count);

        // Set the question to the random index
        currentQuestion = questions[randomQuestionIndex];

        // Remove this question from the list so it will not be repeated (until the game is restarted)
        questions.RemoveAt(randomQuestionIndex);
    }

    private void SetQuestionValues()
    {
        // Set the question text
        questionText.text = currentQuestion.question;

        // Set the category text
        categoryText.text = currentQuestion.category;
    }

    private void SetAnswerValues()
    {
        // Randomize the answer button order
        List<string> answers = RandomizeAnswers(new List<string>(currentQuestion.answers));

        // Set up the answer buttons
        for (int i = 0; i < answerButtons.Length; i++)
        {
            bool isCorrect = false;

            if (i == correctAnswerChoice)
            {
                isCorrect = true;
            }

            answerButtons[i].SetIsCorrect(isCorrect);
            answerButtons[i].SetAnswerText(answers[i]);
        }
    }

    private List<string> RandomizeAnswers(List<string> originalList)
    {
        bool correctAnswerChosen = false;
        List<string> newList = new List<string>();

        for (int i = 0; i < answerButtons.Length; i++)
        {
            int random = Random.Range(0, originalList.Count);

            if (random == 0 && !correctAnswerChosen)
            {
                correctAnswerChoice = i;
                correctAnswerChosen = true;
            }

            newList.Add(originalList[random]);
            originalList.RemoveAt(random);
        }

        return newList;
    }
}

and got the error of ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.Collections.Generic.List1[T].get_Item (System.Int32 index) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0) QuestionSetup.SelectNewQuestion () (at Assets/QuestionSetup.cs:66) QuestionSetup.Start () (at Assets/QuestionSetup.cs:40)

so the question is not got called up to the scene after from different scene, so what’s wrong wit this code?

The stack trace points to Assets/QuestionSetup.cs:66, which is:

currentQuestion = questions[randomQuestionIndex];

And seeing as you validly set randomQuestionIndex based on the count: questions must be empty when the error is thrown.

The logic in GetQuestionAssets must be setting it to an empty list. There are a bunch of ways you can be misusing the Resources API, so just double check what you’re doing there.

my codes its similar to the games like “trivia crack”, so before this code its the roulette code to play first, an the this codes when the category got chosen… the file for the question is already there labeled “Resources”…

Much like a NullReferenceException, this error will only be solved by you debugging and tracking down the issue. Here’s how:

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is and what line of code accesses it <— (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection size

Remember also:

  • a collection with ZERO elements cannot be indexed at all: it is empty
  • you might have more than one instance of this script in your scene/prefab
  • the collection may be used in more than one location in the code
  • indices start at ZERO (0) and go to the count / length minus 1.

This means with three (3) elements in your collection, they are numbered 0, 1, and 2 only.