Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

c# - Copy files from Resources/StreamingAssets to Application.persistentDataPath upon installation

I have txt file which contains data for my maps in game. Problem is that file is stored in Application.persistentDataPath so I can change it even from my android device (created map creator) so how can I include txt file which I created on my PC with basic maps and make it appear in persistentDataPath on my android device when I install application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can put the file in the Resources folder from the Editor folder then read with the Resources API.

TextAsset txtAsset = (TextAsset)Resources.Load("textfile", typeof(TextAsset));
string tileFile = txtAsset.text;

You can check if this is the first time the app is running with this. After that you can copy the loaded data to the Application.persistentDataPath directory.


The Resources folder is known to increase loading times. I suggest you don't use it but it's an option that's worth knowing.

Put the file in StreamingAssets folder then read it with the WWW or UnityWebRequest API and Application.streamingAssetsPath as the path then copy it to Application.persistentDataPath.

Load from 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);
}

then save it to persistentDataPath:

File.WriteAllText(Application.persistentDataPath + "data/MyFile.txt", result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...