在 StreamingAssetsPath 上读取和写入文件

Noo*_*mer 2 c# android json unity-game-engine web

这就是我在 android 中读取文本文件的方式。

#if UNITY_ANDROID
string full_path = string.Format("{0}/{1}",Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
// Android only use WWW to read file
        WWW reader = new WWW(full_path);
        while (!reader.isDone){}

        json = reader.text;

        // PK Debug 2017.12.11
        Debug.Log(json);
 #endif
Run Code Online (Sandbox Code Playgroud)

这就是我从电脑读取文本文件的方式。

#if UNITY_STANDALONE
        string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
        StreamReader reader = new StreamReader(full_path);
        json = reader.ReadToEnd().Trim();
        reader.Close();
#endif
Run Code Online (Sandbox Code Playgroud)

现在我的问题是我不知道如何在移动设备上编写文件,因为我在独立设备上这样做

#if UNITY_STANDALONE
        StreamWriter writer = new StreamWriter(path, false);
        writer.WriteLine(json);
        writer.Close();
 #endif
Run Code Online (Sandbox Code Playgroud)

帮助任何人

更新的问题

这这是我需要获取的流媒体资产文件夹中的 json 文件

Pro*_*mer 5

现在我的问题是我不知道如何在移动设备上编写文件,因为我在独立设备上这样做

您无法保存到此位置Application.streamingAssetsPath是只读的。它是否适用于编辑器并不重要。它是只读的,不能用于加载数据

在此输入图像描述

从 StreamingAssets 读取数据

IEnumerator loadStreamingAsset(string fileName)
{
    string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);

    string result;

    if (filePath.Contains("://") || filePath.Contains(":///"))
    {
        WWW www = new WWW(filePath);
        yield return www;
        result = www.text;
    }
    else
    {
        result = System.IO.File.ReadAllText(filePath);
    }

    Debug.Log("Loaded file: " + result);
}
Run Code Online (Sandbox Code Playgroud)

用法

让我们从屏幕截图中加载“datacenter.json”文件:

void Start()
{
    StartCoroutine(loadStreamingAsset("datacenter.json"));
}
Run Code Online (Sandbox Code Playgroud)

保存数据

适用于所有平台的数据保存路径是Application.persistentDataPath。确保在将数据保存到该路径内之前创建一个文件夹。您问题StreamReader中的 可以用于读取或写入此路径。

保存到Application.persistentDataPath路径:

使用File.WriteAllBytes

Application.persistentDataPath从路径中读取

使用File.ReadAllBytes

请参阅这篇文章,了解如何在 Unity 中保存数据的完整示例。

  • 顺便说一句,这个目录在 Android 上似乎是只读的,因为它被打包到一个 jar 中。但是,它在其他平台上是可写的。文档中的“只读”指的是变量,而不是目录(因为您无法更改路径)。 (2认同)