Why is my code working?

So in the video, the answer to the challenge about changing the text when an incorrect answer is given was:

correctAnswerIndex = question.GetCorrectAnswerIndex();
string correctAnswer = question.GetAnswer(correctAnswerIndex);
questionText.text = correctAnswer;

However, since there was already a class variable called correctAnswerIndex, I had:

questionText.text = question.GetAnswer(correctAnswerIndex);

It worked!!!
And after thinking, I can’t understand why!!!
correctAnswerIndex should be 0 every time because I’m not initializing it!
I’m not feeding it the data from the SO. But I tested by changing the SO data and it worked!!! HOW???

Without seeing the code, it would be quite difficult to say. Show us the class and we might be able to tell you

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

public class Quiz : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI questionText;
    [SerializeField] QuestionSO question;
    [SerializeField] GameObject[] answerButtons;
    int correctAnswerIndex;
    [SerializeField] Sprite defaultAnswerSprite;
    [SerializeField] Sprite correctAnswerSprite;
    void Start()
    {
        questionText.text = question.GetQuestion();

        for(int i = 0;  i < answerButtons.Length; i++)
        {
            TextMeshProUGUI buttonText = answerButtons[i].GetComponentInChildren<TextMeshProUGUI>();
            buttonText.text = question.GetAnswer(i);
        }

    }

    public void OnAnswerSelected(int index)
    {
        Image buttonImage;
        if (index == question.GetCorrectAnswerIndex())
        {
            questionText.text = "Correct!";
            buttonImage = answerButtons[index].GetComponent<Image>();
            buttonImage.sprite = correctAnswerSprite;
        }
        else
        {
            //questionText.text = question.GetAnswer(correctAnswerIndex); This WORKS, but I'm commenting it to match the course
            correctAnswerIndex = question.GetCorrectAnswerIndex();//Part of the changes added by the course, the "correct way" to do it.
            string correctAnswer = question.GetAnswer(correctAnswerIndex);//Part of the changes added by the course, the "correct way" to do it.
            questionText.text = "Sorry, the correct answer was;\n" + correctAnswer;//Part of the changes added by the course, the "correct way" to do it.

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

Hmmm, yes. That would only work if the correct answer was always at index 0.

1 Like

Thank you!

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

Privacy & Terms