安装时将文件从Resources/StreamingAssets复制到Application.persistentDataPath

Ale*_*tic 3 c# android unity-game-engine

我有txt包含游戏中地图数据的文件.问题是文件存储在中,Application.persistentDataPath所以我甚至可以从我的Android设备(创建的地图创建者)更改它,那么如何在我的PC上创建包含基本地图的txt文件,并在persistentDataPath安装时将其显示在我的Android设备上应用?

Pro*_*mer 6

您可以将文件放在Editor文件夹中的Resources文件夹中,然后使用Resources API读取.

TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;
Run Code Online (Sandbox Code Playgroud)

您可以检查这是否是第一次使用应用程序运行.之后,您可以将加载的数据复制到Application.persistentDataPath 目录中.


已知Resources文件夹会增加加载时间.我建议你不要使用它,但这是一个值得了解的选择.

将文件放在StreamingAssets文件夹中,然后使用WWWUnityWebRequestAPI 读取它,Application.streamingAssetsPath然后将其复制到Application.persistentDataPath.

从StreamingAssets加载:

IEnumerator ReadFromStreamingAssets()
{
    string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "MyFile");
    string result = "";
    if (filePath.Contains("://") || filePath.Contains(":///"))
    {
        UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(filePath);
        yield return www.SendWebRequest();
        result = www.downloadHandler.text;
    }
    else
        result = System.IO.File.ReadAllText(filePath);
}
Run Code Online (Sandbox Code Playgroud)

然后将其保存到persistentDataPath:

File.WriteAllText(Application.persistentDataPath + "data/MyFile.txt", result);
Run Code Online (Sandbox Code Playgroud)

  • 我从来没有说过你可以修改它。OP 想知道如何从编辑器中放置文件并在运行时访问它。 (2认同)