Quiz Game tutorial question

How to randomize non-repaeting question?
Hi, Im making a quiz game following official live training tutorial and I would like to set it up so that the questions are showing up randomly in that way that they are not repeating in the currentRound of quiz. I saw in comments of that tutorial that author said we could use Shuffle bag technique but that is a little bit too complicated to implement. Is there any other simpler way to do it? Heres a script from that tutorial that contains ShowQuestion method:

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

public class GameController : MonoBehaviour
{
    public SimpleObjectPool answerButtonObjectPool;
    public Text questionText;
    public Text scoreDisplay;
    public Text timeRemainingDisplay;
    public Transform answerButtonParent;

    public GameObject questionDisplay;
    public GameObject roundEndDisplay;
    public Text highScoreDisplay;

    private DataController dataController;
    private RoundData currentRoundData;
    private QuestionData[] questionPool;

    private bool isRoundActive = false;
    private float timeRemaining;
    private int playerScore;
    private int questionIndex;
    private List<GameObject> answerButtonGameObjects = new List<GameObject>();

    void Start()
    {
        dataController = FindObjectOfType<DataController>();                                // Store a reference to the DataController so we can request the data we need for this round

        currentRoundData = dataController.GetCurrentRoundData();                            // Ask the DataController for the data for the current round. At the moment, we only have one round - but we could extend this
        questionPool = currentRoundData.questions;                                            // Take a copy of the questions so we could shuffle the pool or drop questions from it without affecting the original RoundData object

        timeRemaining = currentRoundData.timeLimitInSeconds;                                // Set the time limit for this round based on the RoundData object
        UpdateTimeRemainingDisplay();
        playerScore = 0;
        questionIndex = 0;

        ShowQuestion();
        isRoundActive = true;
    }

    void Update()
    {
        if (isRoundActive)
        {
            timeRemaining -= Time.deltaTime;                                                // If the round is active, subtract the time since Update() was last called from timeRemaining
            UpdateTimeRemainingDisplay();

            if (timeRemaining <= 0f)                                                        // If timeRemaining is 0 or less, the round ends
            {
                EndRound();
            }
        }
    }

    void ShowQuestion()
    {
        RemoveAnswerButtons();

        QuestionData questionData = questionPool[questionIndex];                            // Get the QuestionData for the current question
        questionText.text = questionData.questionText;                                        // Update questionText with the correct text

        for (int i = 0; i < questionData.answers.Length; i ++)                                // For every AnswerData in the current QuestionData...
        {
            GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();            // Spawn an AnswerButton from the object pool
            answerButtonGameObjects.Add(answerButtonGameObject);
            answerButtonGameObject.transform.SetParent(answerButtonParent);
            answerButtonGameObject.transform.localScale = Vector3.one;

            AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
            answerButton.SetUp(questionData.answers[i]);                                    // Pass the AnswerData to the AnswerButton so the AnswerButton knows what text to display and whether it is the correct answer
        }
    }

    void RemoveAnswerButtons()
    {
        while (answerButtonGameObjects.Count > 0)                                            // Return all spawned AnswerButtons to the object pool
        {
            answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
            answerButtonGameObjects.RemoveAt(0);
        }
    }

    public void AnswerButtonClicked(bool isCorrect)
    {
        if (isCorrect)
        {
            playerScore += currentRoundData.pointsAddedForCorrectAnswer;                    // If the AnswerButton that was clicked was the correct answer, add points
            scoreDisplay.text = playerScore.ToString();
        }

        if(questionPool.Length > questionIndex + 1)                                            // If there are more questions, show the next question
        {
            questionIndex++;
            ShowQuestion();
        }
        else                                                                                // If there are no more questions, the round ends
        {
            EndRound();
        }
    }

    private void UpdateTimeRemainingDisplay()
    {
        timeRemainingDisplay.text = Mathf.Round(timeRemaining).ToString();
    }

    public void EndRound()
    {
        isRoundActive = false;

        questionDisplay.SetActive(false);
        roundEndDisplay.SetActive(true);
    }

    public void ReturnToMenu()
    {
        SceneManager.LoadScene("MenuScreen");
    }
}

You could try adding a new List called something like questionIndexesChosen which keeps track of which questionIndex have come before.
Then add a new method:

void ChooseQuestion()
{
     bool questionChosen = false;
    
     while(questionChosen != true) // While question chosen does not equal true
     {
           int random = Random.Range(0, questionPool.Length); // Choose a random number between 0 and the questionPool length

           if (!questionIndexesChosen.Contains(random)) // If the new list doesn't contain the number
           {
                questionIndexesChosen.Add(random); // Add the number to the list
                questionIndex = random; // Set the questionIndex to the number
                questionChosen = true; // Set questionChosen to true to end the while loop
           }
      }

}

Then either call this method before ShowQuestion() or at the start of the ShowQuestion() method.

That should work but I haven’t actually tested it :slight_smile:

This almost works.
It now chooses a random question from the list of questions (in my case 5 questions). But when it choose question 5 in the list, the quiz ends. So if it starts with question 5 and it is answered the round ends, and there was only one question in the round. The problem lies in this part in the questionsIndex since the last question in the array always will make questionIndex bigger than questionPool.

public void AnswerButtonClicked(bool isCorrect)
    {
        if (isCorrect)
        {
            playerScore += currentRoundData.pointsAddedForCorrectAnswer;                    // If the AnswerButton that was clicked was the correct answer, add points
            scoreDisplay.text = playerScore.ToString();
        }
        if(questionPool.Length > questionIndex + 1)                                            // If there are more questions, show the next question
        {
            questionIndex++;
            ShowQuestion();
        }
        else                                                                                // If there are no more questions, the round ends
        {
            EndRound();
        }
    }
1 Like

In which case add a new int called something like qNumber. Set qNumber to 0 then change the code to:

public void AnswerButtonClicked(bool isCorrect)
    {
        if (isCorrect)
        {
            playerScore += currentRoundData.pointsAddedForCorrectAnswer;                    // If the AnswerButton that was clicked was the correct answer, add points
            scoreDisplay.text = playerScore.ToString();
        }
        if(qNumber < questionPool.Length - 1)                                            // If there are more questions, show the next question
        {
            qNumber++;
            ShowQuestion();
        }
        else                                                                                // If there are no more questions, the round ends
        {
            EndRound();
        }
    }

That should fix the problem because the game is no longer tracking the questionIndex but the actual number of questions asked

I should have seen that.
You are my hero good sir :slight_smile:

1 Like

To millemuz:

Can I see your final coding about this project?.. My game is same as yours, i follow your codes regarding with the random questioning but it doesn’t work with my project. The question hasn’t change. It just repeating the first question until the game’s over. Please :slight_smile: Thank You!..

Here is my code
I’m sorry its a bit messy it’s still a work in progress, but i’ve tried cleaning it up a bit. I hope you can read it.

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


public class GameController : MonoBehaviour
{

    public Text questionDisplayText;
    public Text imageQuestionDisplayText;
    public Text scoreDisplayText;
    public Text scoreDisplayRoundOverText;
    public Text timeRemainingDisplayText;

    public SimpleObjectPool answerButtonObjectPool;

    public Transform answerButtonParent;

    public GameObject questionDisplay;
    public GameObject roundEndDisplay;
    public GameObject correctAnswerPanel;
    public GameObject falseAnswerPanel;
    public GameObject imagePanel;
    public GameObject imageQuestionDisplay;
  
    public AudioSource AudioSource;
    public Image ImageQuestion;
  
    private DataController dataController;
    private RoundData currentRoundData;
    private QuestionData[] questionPool;
  
    private bool isRoundActive;

    private float timeRemaining;
    private int questionIndex;
    private float playerScore;
    private float score1;
    private float score2;
    private int qNumber = 0;

    private List<GameObject> answerButtonGameObjects = new List<GameObject>();
    private List<int> questionIndexesChosen = new List<int>();

    [SerializeField]
    private float timeBetweenQuestions;


    // Use this for initialization
    void Start()
    {
        dataController = FindObjectOfType<DataController>();
        currentRoundData = dataController.GetCurrentRoundData();
        questionPool = currentRoundData.questions;
        timeRemaining = currentRoundData.timeLimitInSeconds;
      
        UpdateTimeRemainingDisplay();
       
        playerScore = 0;
      
        questionIndex = 0;

        ShowQuestion();
        QuestionData questionData = questionPool[questionIndex];
        AudioSource.clip = questionData.QuestionAudio;
        AudioSource.Play();
      
        isRoundActive = true;
       
    }

    private void ShowQuestion()
    {
       
       
        RemoveAnswerButtons();
       
//Choose question is here!
        ChooseQuestion();
        QuestionData questionData = questionPool[questionIndex];
        ImageQuestion.sprite = questionData.QuestionImage2;
        if (ImageQuestion.sprite != null)
        {
            imagePanel.SetActive(true);
            questionDisplay.SetActive(false);
             imageQuestionDisplay.SetActive(true);
         }
        else
        {
            imagePanel.SetActive(false);
            imageQuestionDisplay.SetActive(false);
            questionDisplay.SetActive(true);
           
          
        }
       
        for (int i = 0; i < questionData.answers.Length; i++)
        {
            GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();
            answerButtonGameObjects.Add(answerButtonGameObject);
            answerButtonGameObject.transform.SetParent(answerButtonParent);
           
                        AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
            answerButton.Setup(questionData.answers[i]);
        }

        questionDisplayText.text = questionData.questionText;
        imageQuestionDisplayText.text = questionData.questionText;
    }
   

    void ChooseQuestion()
    {
        bool questionChosen = false;

        while (questionChosen != true) // While question chosen does not equal true
        {
       
            int random = Random.Range(0, questionPool.Length); // Choose a random number between 0 and the questionPool length

            if (!questionIndexesChosen.Contains(random)) // If the new list doesn't contain the number
            {
                questionIndexesChosen.Add(random); // Add the number to the list
                questionIndex = random; // Set the questionIndex to the number
                questionChosen = true; // Set questionChosen to true to end the while loop
            }
        }
       
    }

   
    private void RemoveAnswerButtons()
    {
        while (answerButtonGameObjects.Count > 0)
        {
            answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
            answerButtonGameObjects.RemoveAt(0);
        }
    }

    public void AnswerButtonClicked(bool isCorrect)
    {
        if (isCorrect)
        {
            score1 = timeRemaining -= Time.deltaTime;
            score2 = score1 * 10;
            playerScore += score2;
           
            scoreDisplayText.text = "Score: " + playerScore.ToString("F0");
            scoreDisplayRoundOverText.text = "Score: " + playerScore.ToString("F0");
           
            correctAnswerPanel.SetActive(true);
            questionDisplay.SetActive(false);
            StartCoroutine(TimeBetweenQuestions());
           
           
        }
        else
        {
            falseAnswerPanel.SetActive(true);
            questionDisplay.SetActive(false);
            StartCoroutine(TimeBetweenQuestions());
                       
        }
       
        if (qNumber + 1 < questionPool.Length)                                           
        {
            qNumber++;
            ShowQuestion();
           
        }
        else
        {
            EndRound();
        }

    }

    public void EndRound()
    {
        isRoundActive = false;

        questionDisplay.SetActive(false);
        roundEndDisplay.SetActive(true);
    }

    public void ReturnToMenu()
    {
        SceneManager.LoadScene("MenuScreen");
    }

   

    IEnumerator TimeBetweenQuestions()
    {
       
        yield return new WaitForSeconds(timeBetweenQuestions);
               
        correctAnswerPanel.SetActive(false);
        falseAnswerPanel.SetActive(false);
        timeRemaining = 10;
        QuestionData questionData = questionPool[questionIndex];
        AudioSource.clip = questionData.QuestionAudio;
        AudioSource.Play();

        }

    private void UpdateTimeRemainingDisplay()
    {
        timeRemainingDisplayText.text = Mathf.Round(timeRemaining).ToString();
    }

    // Update is called once per frame
    void Update()
    {
        if (isRoundActive)
        {
            timeRemaining -= Time.deltaTime;
            UpdateTimeRemainingDisplay();

            if (timeRemaining <= 0f)
            {
                Debug.Log("Time is up!!");
                qNumber++;
                ShowQuestion();
              
                timeRemaining = 10;
               
            }

        }
    }
}

To Millemuz:
I manage to read your work Sir and it’s fine. By the way, thank you for this and to your effort. It’s now working, it already choose a random questions. I just missed a little codes hehehe. I am now prepared for the defense this coming Monday… Thank You again sir…

1 Like

Hi Millemuz,
Thanks for sharing your code, I was able to work out how to randomly generate my questions.
One thing though. Did you have the issue that the last question in your hierarchy is asked before the last question it ends the game?

To: mikethingsbetter and n0vember04

Were you able to figure out how to randomize the questions from the original code? And do you mind sharing your project if it’s completed?

hey man how did you mange this scrip >> public GameObject imageQuestionDisplay; did it worked in the array of question?

Hi everyone,
Especially Millemuz!!!
I write some codes about quiz game like yours for random question and this codes work but I have a problem about player score…
Please can you help me…
MY CODES ARE BELOW…Please examine that and feedback me

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

public class GameController : MonoBehaviour
{
    public SimpleObjectPool answerButtonObjectPool;
    public Text questionText;
    public Text scoreDisplay;
    public Text timeRemainingDisplay;
    public Transform answerButtonParent;

    public GameObject questionDisplay;
    public GameObject roundEndDisplay;
    public Text highScoreDisplay;

    private DataController dataController;
    private RoundData currentRoundData;
    private QuestionData[] questionPool;

    private bool isRoundActive = false;
    private float timeRemaining;
    private int playerScore;
    private int questionIndex;
    private int qNumber=0;

    private List<GameObject> answerButtonGameObjects = new List<GameObject>();
    private List<int> questionIndexesChosen=new List<int>();

    void Start()
    {
        dataController = FindObjectOfType<DataController>();                                // Store a reference to the DataController so we can request the data we need for this round

        currentRoundData = dataController.GetCurrentRoundData();                            // Ask the DataController for the data for the current round. At the moment, we only have one round - but we could extend this
        questionPool = currentRoundData.questions;                                            // Take a copy of the questions so we could shuffle the pool or drop questions from it without affecting the original RoundData object

        timeRemaining = currentRoundData.timeLimitInSeconds;                                // Set the time limit for this round based on the RoundData object
        UpdateTimeRemainingDisplay();
        playerScore = 0;
        questionIndex = 0;
        ShowQuestion();
        isRoundActive = true;
    }

    void Update()
    {
        if (isRoundActive)
        {
            timeRemaining -= Time.deltaTime;                                                // If the round is active, subtract the time since Update() was last called from timeRemaining
            UpdateTimeRemainingDisplay();

            if (timeRemaining <= 0f)                                                        // If timeRemaining is 0 or less, the round ends
            {
                qNumber++;
                ShowQuestion ();
            }
        }
    }
    void ChooseQuestion()
    {

        bool questionChoosen = false;

        while (questionChoosen != true) {
       
            int random = Random.Range (0, questionPool.Length);


            if (!questionIndexesChosen.Contains(random)) {
           
                questionIndexesChosen.Add (random);
                questionIndex = random;
                questionChoosen = true;
           
            }
       
        }

    }
    void ShowQuestion()
    {
        RemoveAnswerButtons();
        ChooseQuestion ();
        QuestionData questionData = questionPool[questionIndex];                            // Get the QuestionData for the current question
        questionText.text = questionData.questionText;                                        // Update questionText with the correct text

        for (int i = 0; i < questionData.answers.Length; i ++)                                // For every AnswerData in the current QuestionData...
        {
            GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();            // Spawn an AnswerButton from the object pool
            answerButtonGameObjects.Add(answerButtonGameObject);
            answerButtonGameObject.transform.SetParent(answerButtonParent);
            answerButtonGameObject.transform.localScale = Vector3.one;

            AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
            answerButton.Setup(questionData.answers[i]);                                    // Pass the AnswerData to the AnswerButton so the AnswerButton knows what text to display and whether it is the correct answer
        }
    }

    void RemoveAnswerButtons()
    {
        while (answerButtonGameObjects.Count > 0)                                            // Return all spawned AnswerButtons to the object pool
        {
            answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
            answerButtonGameObjects.RemoveAt(0);
        }
    }

    public void AnswerButtonClicked(bool isCorrect)
    {
        if(qNumber<questionPool.Length-1)                                            // If there are more questions, show the next question
        {
            qNumber++;

            ShowQuestion();
        }
        else                                                                                // If there are no more questions, the round ends
        {
            EndRound();
        }

        if (isCorrect)
        {
            playerScore += currentRoundData.pointsAddedForCorrectAnswers;                    // If the AnswerButton that was clicked was the correct answer, add points
            scoreDisplay.text = "Score:"+playerScore.ToString();
        }


    }

    private void UpdateTimeRemainingDisplay()
    {
        timeRemainingDisplay.text = "Time :"+Mathf.Round(timeRemaining).ToString();
    }

    public void EndRound()
    {
        isRoundActive = false;
        dataController.SubmitNewPlayerScore (playerScore);
        highScoreDisplay.text = "Highscore\n"+dataController.GetHighestPlayerScore ().ToString ();

        questionDisplay.SetActive(false);
        roundEndDisplay.SetActive(true);
    }

    public void ReturnToMenu()
    {
        SceneManager.LoadScene("MenuScreen");
    }
}

Have you tried to add levels? I’ts so confusing when adding levels sigh.