如何检查用户输入是否与文本文件中的单词匹配?

How to check whether user input matches with a word from a text file?

using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
using UnityEngine.UI;

public class LetterRandomiser : MonoBehaviour
{
    public char[] characters; 

    public Text textbox; 

    public InputField mainInputField;

    void Start() /*when the game starts*/
    {
        char c = characters[Random.Range(0,characters.Length)];
        textbox.text = c.ToString(); 
    }

    void Update()
    {
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\lluc\Downloads\words_alpha.txt");

        foreach (string x in lines)
        {
            if (Input.GetKeyDown(KeyCode.Return) 
                && mainInputField.text.Contains(textbox.text) == true
                && mainInputField.text.Contains(x) == true)
            {
                char c = characters[Random.Range(0, characters.Length)];
                textbox.text = c.ToString();
                mainInputField.text = "";
            }
            else if (Input.GetKeyDown(KeyCode.Return) 
                && mainInputField.text.Contains(textbox.text) == false
                && mainInputField.text.Contains(x) == false)
            {
                mainInputField.text = "";
            }
        }
    }
}

参考my game

没有错误,但是当我 运行 游戏时,它非常卡顿。我认为这是因为程序正在读取文本文件 words_alpha.txt,其中包含所有英文单词。

然而,即使它很慢,当我输入一个与文本文件中的任何单词都不匹配的完全随机的单词时,程序仍会接受该单词。

我的代码有问题...

我希望我的代码做什么?

您应该从 Start() 方法而不是 Update() 方法读取文件,因为文件只需要读取一次,而不是每一帧。这将消除延迟。

此外,您还在不必要的每一帧上循环文件。你应该移动

if (Input.GetKeyDown(KeyCode.Return))

foreach 循环之外。您可能应该在 if 语句中调用另一个函数。 Update() 应该看起来更像:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Return) &&
        mainInputField.text.Contains(textbox.text))
    {
        wordIsInFile(mainInputField.text);
        //Remaining code that you want to use
    }

    else
    {
        //whatever needs to be done in the else statement
    }
}

然后是遍历数组的函数:

void wordIsInFile(string word)
{
    foreach (var item in lines)
    {
        if (word == item)
        {
            //Perform tasks on word
            //and whatever else
        }
    }
}

只需在 Start() 之外声明 string[] lines,但在 Start() 中对其进行初始化,以确保它是一个全局变量。这将消除滞后,并且效率更高,因为除非按下 KeyCode 并且 mainInputField 包含一些字符串,否则您不会不断循环数组。