In short, I am getting a null reference at the start of the game because timer.loadNextQuestion is set to false, which leads to the Quiz.Update() method to enter the “else if” statement, which calls “DisplayAnswer(-1)”, which in turn references the still unset “currentQuestion” variable. This happens because the Quiz.Update() method runs before the Timer.Update() method so the Timer still hasn’t run to detect that the next question needs to be set. However, simply changing the loadNextQuestion to start off as “true” won’t work as that causes 2 questions to be removed from the List at the beginning.
I have a basic idea of how to bypass this, but since it isn’t something shown in the lecture, and apparently the lecturer’s code runs perfectly fine (I’ve been watching for the past 20 mins comparing my code and I see no mistakes in it), I was left to wonder if there is maybe another way to solve this that wasn’t shown in the lecture
Quiz.Update()
void Update()
{
timerImage.fillAmount = timer.fillFraction;
if (timer.loadNextQuestion)
{
hasAnsweredEarly = false;
GetNextQuestion();
timer.loadNextQuestion = false;
}
else if (!hasAnsweredEarly && !timer.isAnsweringQuestion)
{
DisplayAnswer(-1);
SetButtonInteractable(false);
}
}
void DisplayAnswer(int index)
{
if (index == currentQuestion.GetCorrentAnswerIndex()) // this here throws the exception
{
questionText.text = "Correct!";
Image buttonImage = answerButtons[index].GetComponent<Image>();
buttonImage.sprite = correctAnswerSprite;
}
else
{
correctAnswerIndex = currentQuestion.GetCorrentAnswerIndex();
questionText.text = "Wrong! The correct answer is:\n" + currentQuestion.GetAnswer(correctAnswerIndex);
Image buttonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();
buttonImage.sprite = correctAnswerSprite;
}
}
Timer.Update()
void Update()
{
UpdateTimer();
}
void UpdateTimer()
{
timerValue -= Time.deltaTime;
if (isAnsweringQuestion)
{
if (timerValue > 0)
{
fillFraction = timerValue / timeToCompleteQuestion;
}
else
{
isAnsweringQuestion = false;
timerValue = timeToShowCorrectAnswer;
}
}
else
{
if (timerValue > 0)
{
fillFraction = timerValue / timeToShowCorrectAnswer;
}
else
{
isAnsweringQuestion = true;
timerValue = timeToCompleteQuestion;
loadNextQuestion = true;
}
}
}