Alternative solution

Here’s an alternative solution for those who’d like it. There’s some unneccessary repeat in the code. The only thing that changes between a correct and incorrect answer is what we set the question.text to. So everything else can be moved outside the if/else block.

    public void OnAnswerSelected(int btnIndex)
    {
        int correctAnswerIndex = question.GetCorrectAnswerIndex();
        Image buttonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();
        buttonImage.sprite = correctAnswerSprite;

        if (btnIndex == correctAnswerIndex)
        {
            questionText.text = "Correct!";
        }
        else
        {
            questionText.text = $"I'm sorry, the correct answer was; \n{question.GetAnswer(correctAnswerIndex)}.";
        }
    }
2 Likes

Another Alternative is using and early return instead of an else.

public void OnAnswerSelected(int answerIndex)
   {
       int correctAnswerIndex = question.GetCorrectAnswerIndex();
       Image ButtonImage = answerButtons[correctAnswerIndex].GetComponent<Image>();
       ButtonImage.sprite = correctAnswerSprite;

       questionText.text = "Correct Answer!";
       if (answerIndex == correctAnswerIndex) return; 
       questionText.text = "The Correct Anwer would have been: \n" + question.GetAnswer(correctAnswerIndex);
   }

Privacy & Terms