参考链接:
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就知道了。