如何在回答并单击"播放"按钮后逐个显示问题



我是Unity的新手,在回答并点击播放按钮后,尝试逐个显示问题

public class PlayGame : MonoBehaviour
{

public string[] questions = {"What is 10+10", "What is 20+20", "What is 30+30", "What is 40+40", "What is 50+50"};
public string[] correctAnswer = {"20", "40", "60", "80" , "100"};
public Text question;
public InputField answer;
public int selection;

// Start is called before the first frame update
void Start()
{
question.text = questions[selection];      
}

public void CheckAnswer()
{
if (answer.text == correctAnswer.ToString())            
{
Debug.Log("Answer is Correct");
//display next question

}
else
{
Debug.Log("Answer is not Correct");
//display next question
}
}
}

这应该是非常直接的

private int selection = -1;
void Start()
{
ShowNextQuestion();     
}
private void ShowNextQuestion()
{
selection++;
if(selection >= questions.Length - 1) 
{
// You said you wanted to restart the questions so simply do
selection = 0;
}
question.text = questions[selection];
}
public void CheckAnswer()
{
if (answer.text.Equas(correctAnswer[selection]))            
{
Debug.Log("Answer is Correct");
}
else
{
Debug.Log("Answer is not Correct");
}
ShowNextQuestion();
}

不过,让我告诉您,通常将问题和答案存储在两个单独的数组中不是一个好主意。

  • 你不能真的确定两个单独的数组总是有相同的长度
  • 在中间添加或删除问题时,您需要加倍努力
  • 想象一下,以后想要随机化问题的顺序。。你记不清哪个答案属于哪个问题

所以我建议你把它们牢固地结合在一起,就像一样

[Serializable]
public class Question
{
// Allow to edit these in the Inspector but nowhere else
[SerializeField] private string _text;
[SerializeField] private string _answer;
// Other classes may only read these
public string Text => _text;
public string Answer => _answer;
// Constructor 
public Question(string text, string answer)
{
_text = text;
_answer = answer;
}
} 

现在,在您的组件中,您可以通过Inspector设置它们,或者通过初始化它们

public Question[] questions = {
new Question("What is 10+10", "20"),
new Question("What is 20+20", "40"),
new Question("What is 30+30", "60"),
new Question("What is 40+40", "80"),
new Question("What is 50+50", "100")
};

然后你当然会相应地更改代码以访问这些

private void ShowNextQuestion()
{
selection++;
if(selection >= questions.Length - 1) 
{
// You said you wanted to restart the questions so simply do
selection = 0;
}
question.text = questions[selection].Text;
}
public void CheckAnswer()
{
if (answer.text.Equals(questions[selection].Answer))           
{
Debug.Log("Answer is Correct");
}
else
{
Debug.Log("Answer is not Correct");
}
ShowNextQuestion();
}

如前所述,这也可以通过在开始前打乱问题来给你的应用程序一点随机性:

using System.Linq;
...
private void Start()
{
questions = questions.OrderBy(q => Random.value).ToArray();
ShowNextQuestion();
}
private void ShowNextQuestion()
{
selection++;
if(selection >= questions.Length - 1) 
{
// You said you wanted to restart the questions so simply do
selection = 0;
questions = questions.OrderBy(q => Random.value).ToArray();
}
question.text = questions[selection].Text;
}

相关内容

  • 没有找到相关文章

最新更新