1. 程式人生 > >[Unity基礎]移動平臺下的檔案讀寫

[Unity基礎]移動平臺下的檔案讀寫

參考連結:

http://www.cnblogs.com/murongxiaopifu/p/4199541.html?utm_source=tuicool#autoid-3-2-0

http://zhaolongchn.blog.163.com/blog/static/1906585042013624115926451/

http://forum.china.unity3d.com/thread-1516-1-1.html

在移動平臺中,一般讀取資源會通過下面這三個路徑:

1.Resources

2.Application.streamingAssetsPath

3.Application.persistentDataPath(同時這個也是可寫的)

重點說下下面這兩個路徑:

1.Application.streamingAssetsPath(只讀)

需要手動建一個StreamingAssets資料夾。在打包時,Resources資料夾下的東西會被壓縮和加密。而StreamingAssets資料夾中的內容則會原封不動的打入包中。

一般在Resources下放預製,StreamingAssets下放二進位制檔案(csv、bin、txt、xml、json、AB包等)

不能通過File類來讀取這個路徑,只能通過WWW類。這是因為在android中,StreamingAssets的東西會被包含在.jar包中(類似於zip壓縮檔案)。

2.Application.persistentDataPath(可讀可寫)

測試:

using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using System.Text;

public class Test : MonoBehaviour {

    public Text text0;
    public Text text1;
    public Text text2;
    public Text text3;
    private string path;
    private string content;

	void Start () 
    {
        //顯示不同平臺下的路徑資訊
        text0.text = Application.dataPath + "\n" + Application.streamingAssetsPath + "\n" + Application.persistentDataPath;

        //讀取StreamingAssets下的檔案
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            path = "file://" + Application.streamingAssetsPath + "/Data/AA.bin";
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            path = Application.streamingAssetsPath + "/Data/AA.bin";
        }   
        StartCoroutine(Load(path, (s) => { content += Application.platform + "\n" + s + "\n"; }));

        //讀取Resources下的檔案
        text2.text = Resources.Load<TextAsset>("CC").text;

        //讀取與寫入Application.persistentDataPath下的檔案
        path = Application.persistentDataPath + "/BB.txt";
        File.WriteAllText(path, "保佑這個也能讀取成功啊~~hello??", Encoding.UTF8);
        text3.text = File.ReadAllText(path, Encoding.UTF8);
	}

    void Update()
    {
        if (!string.IsNullOrEmpty(content)) text1.text = content;
    }

    IEnumerator Load(string url, System.Action<string> action)
    {
        WWW www = new WWW(url);
        yield return www;
        //Debug.Log(www.text);
        action(www.text);
    }

}




Ps:

1.如果讀取的中文為亂碼,則開啟txt檔案,另存為,選擇編碼為UTF-8即可。

2.對於Application.dataPath路徑的東西(不包括StreamingAssets和Resources),除非被引用,否則不會被打包。所以不建議把資料檔案放在這個路徑。具體的自行打包exe就知道了。