[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就知道了。

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值