带有 C# 的 Unity3D - 使用输入字段回答问题

Unity3D with C# - Using Input field to answer question

我正在使用输入字段创建一个统一问答游戏。 如何使用输入字段中的文本来匹配 C# 脚本中的答案?

我不确定你卡在这个问题的哪一部分,但我会尝试回答。

我认为将输入字段与存储的答案进行比较时最重要的是确保比较不区分大小写。您可以通过将两个文本都转换为小写或大写来实现。

var usersAnswer = answerInputField.text.ToLower();
var actualAnswer = "Some Answer".ToLower();

if (usersAnswer == actualAnswer)
{
    Debug.Log("You got it right!");
}

hijinxbassist 的例子很好,但是,我做了一个例子,其中也包括其他部分,比如添加事件监听器和声明字段。

检查单个正确答案:

public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string a1_right_answer = "foo"; // make it public and edit the answer in editor if you like

private void Awake()
{
   // add event listener when button for submitting answer is clicked
   submitAnswerBtn.onClick.AddListener(() => {
      // validate the answer
      if(answerInput.text.ToLower() == a1_right_answer) {
         // success
         Debug.Log("Correct");
      } else {
         Debug.Error("Wrong");
      }
});

检查多个正确答案:

public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor

private string[] a1_right_answers = { "foo", "bar", "foo1", "bar1" }; // multiple right answers

private bool is_right_answer = false; // default value

private void Awake()
{
   // add event listener when button for submitting answer is clicked
   submitAnswerBtn.onClick.AddListener(() => {

      // loop through all the right answers
      for (int i = 0; i < a1_right_answers.Length; i++) 
      {
         // validate the answer
         if(answerInput.text.ToLower() == a1_right_answers[i]) {
            // success
            is_right_answer = true;
            break; 
         }
      }

      // check if the user got the right or wrong answer
      if(is_right_answer) { 
          Debug.Log("Correct");
          is_right_answer = false; // reset for next guess
      } 
      else {
          Debug.Log("Wrong");
          // no need to reset 'is_right_answer' since its value is already default
      }

});