Another NullReferenceException: Object reference not set to an instance of an object

hi everyone, im a newbie in coding as of now, and i cant find what’s wrong with my coding.
im using this coding for my project for end year study.

public class QuestionSetup : MonoBehaviour
{

    public List<QuestionData> questions;
    private QuestionData currentQuestion;

    private TextMeshProUGUI questionText;
    private TextMeshProUGUI categoryText;
    private AnswerButton[] answerButtons;
    private int correctAnswerChoice;

    private void Awake()
    {
        // Get all the questions ready
        GetQuestionAssets();
    }

    // Start is called before the first frame update
    public void Start()
    {
        //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();
    }

    // Update is called once per frame
    void Update()
    {

    }

    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 randon index
        currentQuestion = questions[randomQuestionIndex];
        // Remove this question from the list so it will not be repeared (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++)
        {
            // Create a temporary boolean to pass to the buttons
            bool isCorrect = false;

            // If it is the correct answer, set the bool to true
            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++)
        {
            // Get a random number of the remaining choices
            int random = Random.Range(0, originalList.Count);

            // If the random number is 0, this is the correct answer, MAKE SURE THIS IS ONLY USED ONCE
            if (random == 0 && !correctAnswerChosen)
            {
                correctAnswerChoice = i;
                correctAnswerChosen = true;
            }

            // Add this to the new list
            newList.Add(originalList[random]);
            //Remove this choice from the original list (it has been used)
            originalList.RemoveAt(random);
        }


        return newList;
    }
}

and the error was in between line 24 and 54. did anyone know whats wrong about this line?, also the error was

NullReferenceException: Object reference not set to an instance of an object
QuestionSetup.SetQuestionValues () (at Assets/QuestionSetup.cs:60)
QuestionSetup.Start () (at Assets/QuestionSetup.cs:30)

once again thank you for your time seeing this topic

I mean the error tells you exactly where it happened: Line 60 of the QuestionSetup component.

You’ve removed the imports from the code example you posted, so the line 60 that we can see doesn’t actually line up with anything, so it’s hard to give specific help here.

Nonetheless solving a null ref is always, always the same process:
1: Work out what is null ← the most important step
2: Work out WHY it’s null
3: Stop it being null

1 Like

Newbie or oldbie, the answer for NullRef never changes.

NullReference is the single most common error while programming. Fixing it is always the same.

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D:

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

The basic 3 steps outlined above are:

  1. Identify what is null ← any other action taken before this step is WASTED TIME
  2. Identify why it is null
  3. Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

3 Likes

At my dayjob i have used nullable reference types for a few years now (you need to explicit tell the compiler that null is accepted for a reference type variable).

It works very well and the code becomes much more stable and maintainable. Sadly it wouldnt play nice with unity since the constructor is required to set these fields.

But it would sure had been nice and the code base would benefit greatly from it.

Also now with the new required keyword you dont need to use the constructor but can use object initilizers.

1 Like

Your array is the source of the null references. You’ve defined it and you’re trying to set values for it but you’ve never initialized it.

3 Likes

@justfat_han The most disturbing is that lack of initialisation sometimes doesn’t trigger an error message. You’re lucky it did here.
So, before anything else always make sure your variables have been initialised either by code or in the Inspector if it’s a public or serialised private variable.

Unity manual - Variables and the Inspector

Make it an automatism. :slightly_smiling_face:

2 Likes

That “sometimes” can be reasoned about.

Obviously it only applies to reference types, NOT value types.

Second, you have to actually attempt to dereference (read, write or execute) the null value (obviously), and it must be null at the moment you attempt the dereference.

Unity, C# (and many other contexts) are rife with implicit initialization and part of using the context effectively is to undersatnd initialization.

In the case of Unity, here are SOME of the things might affect initialization:

Serialized / public fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:

  • what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)

  • what may be saved with the prefab

  • what may be saved with the prefab override(s)/variant(s)

  • what may be saved in the scene and not applied to the prefab

  • what may be changed in the scene and not yet saved to disk

  • what may be changed in OnEnable(), Awake(), Start(), or even later

Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.

Here’s the official discussion: https://blog.unity.com/technology/serialization-in-unity

If you must initialize fields, then do so in the void Reset() method, which ONLY runs in the UnityEditor.

Here’s more nitty-gritty on serialization:

Field initializers versus using Reset() function and Unity serialization:

To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute

3 Likes