Hello GameDev.tv community,
I’m working on the Unity Quiz Master and facing an issue where my OnAnswerSelected
method is not being called upon button click. Below is the code snippet from my Quiz.cs
script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro; // TextMeshProUGUI
using UnityEngine.UI; // Image
public class Quiz : MonoBehaviour
{
[SerializeField] TextMeshProUGUI questionText; // TextMeshProUGUI
[SerializeField] QuestionSO question; // QuestionSO is a ScriptableObject
[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)
{
Debug.Log("OnAnswerSelected method has been called, the selected answer index is: " + correctAnswerIndex);
if(index == question.GetCorrectAnswerIndex())
{
questionText.text = "Correct!";
Image buttonImage = answerButtons[index].GetComponent<Image>();
buttonImage.sprite = correctAnswerSprite;
}
else
{
questionText.text = "Incorrect!";
}
}
}
I’ve set up the UI buttons in the Unity editor and assigned the OnAnswerSelected
method to the OnClick
event of these buttons. However, when I click on any answer button, nothing happens, and the debug log message doesn’t appear in the console.
Here are the steps I’ve taken:
- Ensured the
Quiz
script is attached to the relevant GameObject. - Checked that the
OnClick
event for each button is set toQuiz -> OnAnswerSelected (int)
.
I’m unsure why the method is not being triggered. Any insights or suggestions would be greatly appreciated!
Attached are screenshots from my Unity setup:
Thank you!