You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PC可读取文本文件Android却不行?Wordle克隆游戏遇读取异常

Android端无法读取单词列表的问题解决

问题原因

在Android平台,Application.dataPath指向的是APK安装包内部的路径,APK本质是压缩文件,File类无法直接读取压缩包内的文件,导致File.Exists(path)返回false,possibleWordsList始终未初始化。后续直接访问possibleWordsList会触发空引用异常,导致脚本终止。

解决方案

方法一:使用TextAsset直接加载(最简单)

  1. 将possibleWordsList.txt放在Unity项目的Assets目录下(任意子目录均可)。
  2. 在脚本中添加public TextAsset wordListText;字段,然后在Unity编辑器的Inspector面板中,将txt文件拖拽到这个字段完成赋值。
  3. 修改Start方法代码:
void Start()
{
    possibleWordsList = new List<string>();
    
    // 分割文本内容为每行单词,过滤空行
    string[] lines = wordListText.text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
    possibleWordsList.AddRange(lines);
    
    // 确保列表不为空再随机取词
    if (possibleWordsList.Count > 0)
    {
        targetWord = possibleWordsList[UnityEngine.Random.Range(0, possibleWordsList.Count)];
    }
    else
    {
        Debug.LogError("单词列表为空,请检查TextAsset是否正确赋值");
    }
}

方法二:使用StreamingAssets文件夹(适合动态读取场景)

  1. 在Unity项目的Assets目录下创建StreamingAssets文件夹(名称必须完全一致),将possibleWordsList.txt放入其中。
  2. 使用UnityWebRequest读取文件内容(Android平台必须用这种方式读取StreamingAssets内的文件):
using UnityEngine.Networking;
using System.Collections;

void Start()
{
    StartCoroutine(LoadWordList());
}

IEnumerator LoadWordList()
{
    string path = Path.Combine(Application.streamingAssetsPath, "possibleWordsList.txt");
    UnityWebRequest request = UnityWebRequest.Get(path);
    
    yield return request.SendWebRequest();
    
    if (request.result == UnityWebRequest.Result.Success)
    {
        possibleWordsList = new List<string>();
        string[] lines = request.downloadHandler.text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
        possibleWordsList.AddRange(lines);
        
        if (possibleWordsList.Count > 0)
        {
            targetWord = possibleWordsList[UnityEngine.Random.Range(0, possibleWordsList.Count)];
        }
        else
        {
            Debug.LogError("单词列表为空,请检查文件内容");
        }
    }
    else
    {
        Debug.LogError($"读取单词列表失败:{request.error}");
    }
}

额外注意事项

  • 随机索引要基于列表实际长度:原代码中Random.Range(0, 1000)会在列表长度不足1000时触发索引越界,必须改为Random.Range(0, possibleWordsList.Count)。
  • 确保txt文件编码为UTF-8,避免字符乱码;同时清理文件末尾的空行,避免加载无效空字符串。

内容的提问来源于stack exchange,提问作者thepyguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:24:01