Quiz Master Complete C# Unity Game Developer 2D course

Hello, in the Complete C# Unity Game Developer 2D course, on the Section 4 in the Script im developing the category where you can choose wich set of questions you want to answer, the problem is that i get this error in the console NullReferenceException: Object reference not set to an instance of an object. in the Script LeagueOfLegendsButton.

//QUIZ CLASS
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using TMPro;

using UnityEngine.UI;

public class Quiz : MonoBehaviour

{

[Header("Questions")]

[SerializeField] TextMeshProUGUI questionText;

[SerializeField] List<QuestionSO> questionsLol = new List<QuestionSO>();

[SerializeField] List<QuestionSO> questionsJava = new List<QuestionSO>();

QuestionSO currentQuestion;

[Header("Answers")]

[SerializeField] GameObject[] answerButtons;

int correctAnswerIndex;

bool hasAnweredEarly = true;

[Header("Button Colors")]

[SerializeField] Sprite defaultAnswerSprite;

[SerializeField] Sprite correctAnswerSprite;

[Header("Timer")]

[SerializeField] Image timerImage;

Timer timer;

[Header("Scoring")]

[SerializeField] TextMeshProUGUI scoreText;

ScoreKeeper scoreKeeper;

[Header("ProgressBar")]

[SerializeField] Slider progressBar;

public bool isComplete;

Image buttonImage;

public bool lolQuestions = true;

public bool javaQuestions = true;

void Awake()

{

  //if(lolQuestions == false){

 

  timer = FindObjectOfType<Timer>();

  scoreKeeper = FindObjectOfType<ScoreKeeper>();

  progressBar.maxValue = questionsLol.Count;

  progressBar.value = 0;

  /*}

  else if (javaQuestions == false)

  {

  timer = FindObjectOfType<Timer>();

  scoreKeeper = FindObjectOfType<ScoreKeeper>();

  progressBar.maxValue = questionsJava.Count;

  progressBar.value = 0;

  }*/

}

void Update()

{

   

    timerImage.fillAmount = timer.fillFraction;

    if(timer.loadNextQuestion)

    {

        if(progressBar.value == progressBar.maxValue)

    {

        isComplete = true;

        return;

    }

        hasAnweredEarly = false;

        GetNextQuestion();

        timer.loadNextQuestion = false;

    }

    else if(!hasAnweredEarly && !timer.isAnsweringQuestion)

    {

       

        DisplayAnswer(-1); // -1 viene usato per cadere direttamente nel else statement

        SetButtonState(false);

    }

   

}

public void OnAnswerSelected(int index)

{

    hasAnweredEarly = true;

    DisplayAnswer(index);

    SetButtonState(false);

    timer.CancelTimer();

    scoreText.text = "Score: " + scoreKeeper.CalculateScore() + "%";

}

void DisplayAnswer(int index) // cambia il colore della risposta esatta modificando lo sprite dell'Image

{

    if(index == currentQuestion.GetCorrectAnswerIndex())

    {

        questionText.text = "Correct!";

        buttonImage = answerButtons[index].GetComponent<Image>();

        buttonImage.sprite = correctAnswerSprite;

        scoreKeeper.IncrementCorrectAnswers();

    }

    else

    {

        correctAnswerIndex = currentQuestion.GetCorrectAnswerIndex();

        string correctAnswer = currentQuestion.GetAnswer(correctAnswerIndex);

        questionText.text = "I'm sorry but the correct answer is\n" + correctAnswer;

        buttonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();

        buttonImage.sprite = correctAnswerSprite;

       

    }

}

void GetNextQuestion()

{

    //if(lolQuestions == false){

        if(questionsLol.Count > 0)

        {

            SetButtonState(true);

            SetDefaultButtonSprites();

            GetRandomQuestion();

            DisplayQuestion();

            progressBar.value++;

            scoreKeeper.IncrementQuestionSeen();

        }

    /*}

    else if(javaQuestions == false)

    {

        if(questionsLol.Count > 0)

        {

            SetButtonState(true);

            SetDefaultButtonSprites();

            GetRandomQuestion();

            DisplayQuestion();

            progressBar.value++;

            scoreKeeper.IncrementQuestionSeen();

        }

    }*/

}

void GetRandomQuestion()

{

    //if(lolQuestions == false){

        int index = Random.Range(0, questionsLol.Count);

        currentQuestion = questionsLol[index];

        if(questionsLol.Contains(currentQuestion))

        {

            questionsLol.Remove(currentQuestion);

        }

    /*}

    else if (javaQuestions == false)

    {

        int index = Random.Range(0, questionsJava.Count);

        currentQuestion = questionsJava[index];

        if(questionsJava.Contains(currentQuestion))

        {

            questionsJava.Remove(currentQuestion);

        }

    }*/

}

void DisplayQuestion()

{

    questionText.text = currentQuestion.GetQuestion();

    for(int i = 0; i <answerButtons.Length; i++){ // raggruppa tutte le risposte del component child Text del component padre QuizCanvas e inserisce la risposta

    // in ogni testo recuperato

        TextMeshProUGUI buttonText = answerButtons[i].GetComponentInChildren<TextMeshProUGUI>();

        buttonText.text = currentQuestion.GetAnswer(i);

       

    }

}

void SetButtonState(bool state)// disabilità il bottone dopo aver risposto alla domanda

{

    for (int i = 0; i < answerButtons.Length; i++)

    {

        Button button = answerButtons[i].GetComponent<Button>();

        button.interactable = state;

    }

}

void SetDefaultButtonSprites() // cambia il colore delle risposte modificando lo sprite dell'Image



{

    for (int i = 0; i < answerButtons.Length; i++)

    {

        buttonImage = answerButtons[i].GetComponent<Image>();

        buttonImage.sprite = defaultAnswerSprite;

    }

}

}

//LeagueOfLegendsButton CLASS
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class LeagueOfLegendsButton : MonoBehaviour

{

Quiz quiz;

SchermataPrincipaleScript schermataPrincipaleScript;

void Awake()

{

    quiz = FindObjectOfType<Quiz>();

    schermataPrincipaleScript = FindObjectOfType<SchermataPrincipaleScript>();

}

// Start is called before the first frame update

void Start()

{

   

}

// Update is called once per frame

void Update()

{

   

}

public void ChangeCanvasLol()

{

    quiz.gameObject.SetActive(true);

    schermataPrincipaleScript.gameObject.SetActive(false);

    quiz.lolQuestions = false;

}

}

Hi Emanuele,

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

Hope this helps :slight_smile:


See also:

sorry but i can’t find the solution. i modified the description, i appreciate if u can control the code.

Have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture? Have you already tried to add Debug.Logs to your code to see what is going on during runtime?

this is something that i decided to implement alone, and there’s not in the course. The problem seems to be that i didn’t use FindObjectOfType, but i actually did as u can see in the LeagueOfLegendsButton class.

How are you getting on with this, @Emanuele?

The problem is solved

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms