【问题标题】:Iterating and reading text files from folder on Android从Android上的文件夹中迭代和读取文本文件
【发布时间】:2018-08-03 15:07:23
【问题描述】:

我在 Unity 中为 android 制作了一个文字游戏应用程序,玩家必须从之前加载到游戏中的类别中找到一个单词。

我加载类别的方式是: 在 Assets 中有一个名为 Categories 的文件夹,我遍历该文件夹并将每个文本文件作为一个类别读取。

类别存储在字典中,其中键是文件的名称,值是文件的每一行作为数组元素。

它在 PC 上运行良好,但在 android 上没有运气。尝试将路径更改为 "公共字符串 categoriesDirectoryPath = Application.persistentDataPath +"Categories";"还是不行。

原始路径是“资产/类别”

使用文件值启动字典的代码是(发生在 GameManager 的 Awake() 上):

 private Dictionary<string, string[]> createCategories(string directoryPath)
    {
        Dictionary<string, string[]> categories = new Dictionary<string, string[]>();
        string[] categoryPaths = Directory.GetFiles(directoryPath);
        foreach (string path in categoryPaths)
        {
            if (!path.EndsWith("meta")) {
                Debug.Log(path);
                string categoryName = Path.GetFileNameWithoutExtension(path);
                Debug.Log(categoryName);
                string[] categoryData = File.ReadAllLines(path).ToArray();
                categories.Add(categoryName, categoryData);
            }
        }
        return categories;
    }

有没有办法在构建 APK 后迭代文件夹并读取 Assets/Categories 中的文本文件?

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    有没有办法迭代文件夹并读取文本文件 构建 APK 后是否在 Assets/Categories 中?

    没有。

    如果您想从项目中访问,在构建中,您有两种选择:

    1. 将文件放在名为“Resources”的文件夹中,然后使用资源读取文件并将其复制到Application.persistentDataPath 路径。通过将其复制到Application.persistentDataPath,您将能够对其进行修改。 “资源”中的任何内容都是只读的。

    2。将文件放入 StreamingAssets 文件夹,然后使用UnityWebRequest、WWW 或System.IO.File API 读取它。有了这个,你可以复制到Application.persistentDataPath。

    Here 是一篇文章,其中包含有关如何执行这两项操作的代码示例。


    3.AssetBundle(根据性能和加载原因推荐)。

    您可以将文件构建为 AssetBundle,然后将它们放入 StreamingAssets 文件夹并使用AssetBundle API 读取它。

    Here 是构建和读取 AssetBundle 数据的完整示例。

    【讨论】:

    • 我正在使用相同的方法。它正在工作。如果您在 webgl 上,您还应该使用 WWW 从 StreamingAssets 文件夹中读取文件,而 ios 和 pc(mac 和 linux)可以使用常规文件复制将文件从 StreamingAssets 文件夹移动到 persistentDataPath
    • Resources 听起来是个不错的选择,但是我不希望指定每个类别(文件),因为它必须是硬编码的。是否可以上传资源文件夹中的所有资源?
    • @RonTang 这适用于所有平台上的 Resources 文件夹,但适用于某些平台上的 StreamingAssets。请注意我提到了UnityWebRequest、WWW 和System.IO.File。 UnityWebRequest 和 WWW 现在基本相同,但现在推荐使用 UnityWebRequest。 UnityWebRequest 应该在 Android 和 WebGL 上使用,System.IO.File 应该在其他平台上使用。
    • @RonTang 我在答案中提供的链接表明您可以通过检查:// 或:/// 存在的路径来确定使用哪一个。
    • @DorMoshe “我不希望指定每个类别(文件),因为它必须是硬编码的” 然后使用答案中也提到的 StreamingAssets。如果您有很多资源数据,我建议您使用我的答案中排名第三的 AssetBundle。
    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多