Alternative solution for challenge with less variables

Hi, I believe this solution to the challenge works better so you don’t need the int correctAnswerIndex; variable. Let me know if you see any glaring issues. :smiley:

Here is it working in Unity:
4fO9FFi

Here is the full code:

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

public class Quiz : MonoBehaviour
{
    [SerializeField] QuestionSO question;
    [SerializeField] TextMeshProUGUI questionText;
    [SerializeField] GameObject[] answerButtons;
    //int correctAnswerIndex; Not needed with my solution
    [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
        {
            //Sets question text to the correct answers using GetAnswer method with GetCorrectAnswerIndex method as variable.
            questionText.text = "The answer was:\n" + question.GetAnswer(question.GetCorrectAnswerIndex());
            //Sets the button's image using same GetCorrectAnswerIndex method as variable.
            buttonImage = answerButtons[question.GetCorrectAnswerIndex()].GetComponent<Image>();
            buttonImage.sprite = correctAnswerSprite;
        }
    }

}
2 Likes

Awesome code! Great job finding an alternative solution!

1 Like

Privacy & Terms