Unity3D:数据持久化存储解决方案(一)-Txt

unity3d开发对Txt文件的读写

1.引入库

本地的txt文件的读取,需要引入System.IO

using System.IO;

2.读入数据

从StreamingAsset文件夹读取数据

public static string ReadFileFromStreamingAsset(string File_Name)
    {
        string File_Path;
        if (Application.platform == RuntimePlatform.Android)
            File_Path = "jar:file://" + Application.dataPath + "!/assets/" + File_Name;
        else
            File_Path = Application.dataPath + "/StreamingAssets/" + File_Name;
        WWW www = new WWW(File_Path);
        while (!www.isDone) { }
        if (www.error == null) return www.text;
        else return www.error;
    }

这里需要注意的是平台不同,读取文件的路径需要做区分

从PersistentDataPath读取数据,需要先从StreamingAssets中拷贝一份

public static void CopyFileFromStreamingAsset(string File_Name)
    {
        string From_Path;
        if (Application.platform == RuntimePlatform.Android)
            From_Path = "jar:file://" + Application.dataPath + "!/assets/" + File_Name;
        else
            From_Path = Application.dataPath + "/StreamingAssets/" + File_Name;
        string To_Path = Application.persistentDataPath + "/" + File_Name;
        WWW www = new WWW(From_Path);
        while (!www.isDone) { }
        if (www.error == null)
        	File.WriteAllBytes(To_Path, www.bytes);
        
    }
public static string[] ReadFileLines(string file_name)//读取
    {
        string path = Application.persistentDataPath + "/" + file_name;
        if (!File.Exists(path))  { CopyFileFromStreamingAsset(file_name); };
        return File.ReadAllLines(path);
    }

3.写入数据

游戏中产生的变更文件或游戏中生成的新文件存入PersistentDataPath

public static void CreateFileToPersistenDataPath(string File_Name, string Str_info)
    {
        StreamWriter sw;
        FileInfo t = new FileInfo(Application.persistentDataPath + "/" + File_Name);
        if (!t.Exists)
        {
            sw = t.CreateText();
        }
        else
        {
            t.Delete();
            t.Refresh();
            sw = t.AppendText();
        }
        sw.Write(Str_info);
        sw.Dispose();
        sw.Close();
        
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值