I'm trying to make a mini quiz game, but I'm stuck. I'm showing questions, randomly, but the first question never comes up. Furthermore, when I set the size of the questionsNumberChoosen
array to 10
and run the game, it crashes.
public struct Question
{
public string questionText;
public string[] answers;
public int correctAnswerIndex;
// .. we also construct the Question, directly providing all values.
}
public Text questionText;
public Button[] answerButtons;
private Question currentQuestion;
private Question[] questions = new Question[10];
private int[] questionNumbersChoosen = new int[9];
private int questionsFinished;
void Start ()
{
questions [0] = new Question("1", new string[]{"A", "A", "A", "A", "A" }, 2);
questions [1] = new Question("2", new string[]{"A", "A", "A", "A", "A" }, 0);
questions [2] = new Question("3", new string[]{"A", "A", "A", "A", "A" }, 4);
questions [3] = new Question("4", new string[]{"A", "A", "A", "A", "A" }, 0);
questions [4] = new Question("5", new string[]{"A", "A", "A", "A", "A" }, 0);
questions [5] = new Question("6", new string[]{"A", "A", "A", "A", "A" }, 2);
questions [6] = new Question("7", new string[]{"A", "A", "A", "A", "A" }, 0);
questions [7] = new Question("8", new string[]{"A", "A", "A", "A", "A" }, 4);
questions [8] = new Question("9", new string[]{"A", "A", "A", "A", "A" }, 0);
questions [9] = new Question("10", new string[]{"A", "A", "A", "A", "A" }, 0);
setQuestionIndex ();
assignQuestion (questionNumbersChoosen[0]);
}
void assignQuestion(int questionNum)
{
currentQuestion = questions [questionNum];
questionText.text = currentQuestion.questionText;
for (int i=0; i < answerButtons.Length; i++)
answerButtons[i].GetComponentInChildren<Text>().text
= currentQuestion.answers [i];
}
public void checkAnswer(int buttonNum)
{
if (buttonNum == currentQuestion.correctAnswerIndex)
print ("Correct!");
else
print ("Incorrect!");
if (questionsFinished < (questionNumbersChoosen.Length - 1))
moveToNextQuestion ();
}
void setQuestionIndex()
{
for (int i = 0; i < questionNumbersChoosen.Length; i++)
{
int questionNum = Random.Range (0, questions.Length);
if (!isContain (questionNumbersChoosen, questionNum))
questionNumbersChoosen [i] = questionNum;
else
i--;
}
}
bool isContain (int[] num, int numbers)
{
for (int i=0; i < num.Length; i++)
{
if (numbers == num [i])
return true;
}
return false;
}
public void moveToNextQuestion()
{
assignQuestion (questionNumbersChoosen
[questionNumbersChoosen.Length -1 - questionsFinished++]);
}
while
loop inside the for loop instead of doing that uglyi--;
. That said, it is really easy for you to find what the problem is : Put a breakpoint in your loop and check what is happening \$\endgroup\$