Unity拼词游戏Text Asset运行时读取异常,数组长度为0求助
问题:拼词游戏中Text Asset加载后数组长度为0的异常
我正在为学校论文开发一款类似Bookworm的拼词游戏,遇到异常问题:运行时validWords数组长度始终为0,Unity返回的Text Asset处理后也出现这个问题。
相关代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; using UnityEngine.SceneManagement; using System.Data; public class WordChecker : MonoBehaviour { public string[] validWords; private Row row; private string word; private List<LetterDragTiles> droppedTiles = new List<LetterDragTiles>(); public int EnemyMaxHealth; public int EnemyCurrentHealth; public int PlayerMaxHealth; public int PlayerCurrentHealth; public int amount; public int HostileAmount; [SerializeField] GameObject panel; private void Awake() { row = GetComponentInChildren<Row>(); } private void Start() { LoadData(); EnemyCurrentHealth = EnemyMaxHealth; PlayerCurrentHealth = PlayerMaxHealth; } private void LoadData() { TextAsset textFile = Resources.Load("Referentials") as TextAsset; string[] lines = textFile.text.Split("\n"); Debug.Log(textFile.text); Debug.Log("Number of words in dictionary: " + validWords.Length); validWords = new string[lines.Length]; for (int i =0; i < lines.Length; i++) { validWords[i] = lines[i].Trim(); } } public void AddDroppedTile(LetterDragTiles tile) { droppedTiles.Add(tile); UpdateRow(); } private void UpdateRow() { // Clear existing tiles from the row foreach (var tile in row.tiles) { tile.SetLetter(' '); } // Add letters from dropped tiles to the row for (int i = 0; i < droppedTiles.Count; i++) { row.tiles[i].SetLetter(droppedTiles[i].LetterBlock); } } public void SubmitRow(Row row) { word = row.word; Debug.Log("Word formed: " + word); if (string.IsNullOrEmpty(word)) { Debug.Log("Please enter a word"); return; } if (isValidWord(word)) { EnemyCurrentHealth -= amount; if (EnemyCurrentHealth <= 0) { LoadScene(); } } else { Debug.Log("No such word"); PlayerCurrentHealth -= HostileAmount; if (PlayerCurrentHealth <= 0) { panel.SetActive(true); } } } private bool isValidWord(string word) { for (int i = 0; i < validWords.Length; i++) { string validWord = validWords[i].Trim(); if (validWord == word.Trim()) { Debug.Log("Word exists"); return true; } } Debug.Log("The word doesn't exist in the index"); return false; } public void LoadScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex+ 1); } }
Debug输出
Number of words in dictionary: 0 UnityEngine.Debug:Log (object)
WordChecker:LoadData () (at Assets/Scripts/WordChecker.cs:43)
WordChecker:Start () (at Assets/Scripts/WordChecker.cs:33)
错误分析与修复方案
1. 日志打印时机错误
你当前的Debug.Log("Number of words in dictionary: " + validWords.Length);写在validWords = new string[lines.Length];之前,此时validWords还未被赋值(初始默认是长度为0的数组),所以必然输出0。
2. Text Asset分割逻辑缺陷
Windows系统的换行符是\r\n,仅用Split("\n")分割会导致部分行末尾带有\r字符,甚至如果文件有空行,会生成空元素,最终导致validWords包含无效内容或长度异常。
3. 缺少文件加载有效性校验
未判断Resources.Load是否成功加载文件,若文件路径或名称错误,会导致空引用错误,后续逻辑也会失效。
修复后的LoadData方法
private void LoadData() { // 加载Text Asset并校验是否成功 TextAsset textFile = Resources.Load("Referentials") as TextAsset; if (textFile == null) { Debug.LogError("无法加载Referentials文件,请检查Assets/Resources文件夹下是否存在该文件,且文件名完全匹配(大小写敏感)"); return; } // 处理不同系统的换行符,同时移除空行 string[] lines = textFile.text.Split(new[] {'\n', '\r'}, System.StringSplitOptions.RemoveEmptyEntries); Debug.Log("Text Asset原始内容:\n" + textFile.text); Debug.Log("分割后有效行数:" + lines.Length); // 初始化并赋值validWords validWords = new string[lines.Length]; for (int i = 0; i < lines.Length; i++) { validWords[i] = lines[i].Trim(); } // 在赋值完成后打印实际长度 Debug.Log("字典中单词总数:" + validWords.Length); }
额外排查步骤
- 确认
Referentials文件必须放在Assets/Resources文件夹下,文件名完全匹配(注意大小写,比如不能写成referentials或Referentials.txt)。 - 检查Text Asset的内容:确保文件中有实际的单词,每行一个,没有大量空行。
- 验证文件编码:在Unity Inspector面板中选中该文件,设置编码为UTF-8,避免乱码导致分割异常。
内容的提问来源于stack exchange,提问作者RGVC
相关产品推荐
相关产品推荐

