[英]How can I read and find specific information in a txt file and compare it to strings unity
我正在嘗試在統一 c# 中制作類似於拼字游戲的游戲。 我使用的統一版本是2019.4。 我有一個包含 58110 個單詞的 txt 文件。 我想要一個統一腳本來查看 txt 中是否包含字符串(字符串是玩家輸入的單詞)。 我查看了一些教程,但沒有一個能夠提供我一直在尋找的東西,我是初學者嘗試自己做(對不起)那么最好的方法是什么? (到目前為止我還沒有嘗試過任何東西,因為教程的結果並不令人滿意,當然我不知道如何自己做)。
假設 unity 可以訪問這些調用。 您可以只使用File.ReadAllines
然后將其轉換為HashSet
,使用Contains
進行快速查找。
var hashSet = File
.ReadAllLines("SomeFileName")
.ToHashSet();
// if you want case insensitivity
//.ToHashSet(StringComparer.OrdinalIgnoreCase);
if (hashSet .Contains(SomeUserInputedString))
Debug.Log("You Won");
如果 unity 沒有ToHashSet
,你可以使用它的構造函數
var hashSet = new HashSet(File.ReadAllLines("SomeFileName")) ;
其他資源
打開一個文本文件,將文件的所有行讀入一個字符串數組,然后關閉文件。
使用比較器從
IEnumerable<T>
創建HashSet<T>
以比較鍵。
確定 HashSet object 是否包含指定的元素。
這是完成您所要求的一種方法:
public class Words : MonoBehaviour
{
[SerializeField] private TextAsset words;
[SerializeField] private bool useCase = false;
private HashSet<string> wordHashes = new HashSet<string> ( );
void Start()
{
// Creates the hashset data set at the start of the game.
var words = this.words.text.Split ( new [ ] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
for ( int i = 0, count = words.Length; i < count; i++ )
{
Debug.Log ( $"Read {words[i]} from the words list." );
wordHashes.Add ( useCase ? words [ i ] : words [ i ].ToLower ( ) );
}
Debug.Log ( $"Hashset contains One : {Contains ( "One" )}" );
}
public bool Contains ( string word )
{
return wordHashes.Contains ( useCase ? word : word.ToLower ( ) );
}
}
它利用了在編譯時將與您的游戲一起打包的TextAsset
資產。 在適當的時候,您可以解析words
TextAsset
,將單詞拉出並放入HashSet
。 包含Contains
方法可以很容易地查詢單詞是否包含在words
列表中。
一種優化是在讀入所有單詞后序列化實際的 HashSet 數據。這樣可以省去在游戲開始時創建 HashSet 的麻煩,而重新啟動游戲時可能需要相當長的時間。 在運行時生成 hash 也會產生一些垃圾,這些垃圾將在某個階段被清除。 HashSet 數據可以從編輯器腳本存儲到 ScriptableObject 之類的東西中。 但是,這不是問題中所要求的,只是我的偏好。
這是關於TextAsset
的 Unity 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.