C# 读取文本文件停止工作 - 使用 Unity

本文关键字:使用 Unity 停止工作 文件 读取 取文本 | 更新日期: 2023-09-27 18:35:24

我有一个程序,它可以读取目录中任意数量的.txt文件并将它们组合在一个列表中,然后此列表一次显示给用户一个。用户此时做出决定并存储反应时间。最近,文本导入脚本无缘无故停止工作。我已经几个月没有更改任何文本导入代码了。

我已经检查了文件中读取的代码,根本没有被识别。

仅供参考,这是Unity计划的一部分。

文本导入

using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
public class TextImport : MonoBehaviour {
    public static List<string> TextLines;
    bool FileRead = false;
    // Use this for initialization
    void Awake() {
        TextLines = new List<string>();
        string path;
        if(Application.platform == RuntimePlatform.WindowsEditor)
        {
            path = Application.dataPath + "/Resources/";
        }
        else if (Application.platform == RuntimePlatform.WindowsPlayer)
        {
            path = Application.dataPath;
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            FileRead = true;
            path = "/StroopTest/";
            TextAsset Allfiles = Resources.Load("Android/AllText") as TextAsset;
            string[] AllLinesAndroid = Allfiles.text.Split("'n"[0]);
            foreach (string Line in AllLinesAndroid)
            {
                TextLines.Add(Line);
                break;
            }
        }
        else
        {
            path = Application.dataPath;
        }
        if (!FileRead)
        {
            DirectoryInfo info = new DirectoryInfo(path);
            FileInfo[] fileInfo = info.GetFiles("*.txt");//I've changed the "*.txt" to nothing to read all files instead of just .txt files
            foreach (FileInfo file in fileInfo)
            {
                //I created another List here to store the file names that were read, however none were.
                string[] AllLines = File.ReadAllLines(file.FullName);
                foreach (string line in AllLines)
                {
                    TextLines.Add(line);
                }
            }
        }
    }
}

C# 读取文本文件停止工作 - 使用 Unity

我建议使用 Application.persistentDataPath .

Application.dataPath是一个只读目录,您可以在其中(如果打包这样做)在那里找到与游戏相关的资产。

但是,Application.persistentDataPath 是一个可写目录,并返回一个路径(不同平台不同),您可以在运行时在其中添加内容(例如:写入文件、下载文件等)。

我希望这有所帮助。