关于Resources中的Json文件的读取

废话不多说,直接上代码,这里有几个注意点,看了几个文章都没提到,自己碰到了所以特别标注一下,其他内容别的博客都能找到。

读取方法:

方法1

public void ReadJson()
{        
    string url = "Data/" + GameManage.Instance.Scene.ToString();//注意,路径末尾不能加后缀,即不加.json,会报错
    TextAsset text = Resources.Load<TextAsset>(url);
    if (text != null)
    {
        SaveData data = JsonMapper.ToObject<SaveData>(text.text);//这里是用的litjson读取,也可以用unity自带的类读取
        //GameManage.Instance.StartRestore(data);//还原数据的一个方法,不用管
    }
    else
    {
        Debug.LogError("当前读取的文件不存在" + url);
    }
}

方法2 

    public void ReadJson()
    {
        string url = Application.dataPath + "/Resources/Data/" +GameManage.Instance.Scene.ToString() + ".json";//这里必须加后缀,不加报错
        if (File.Exists(url))
        {
            StreamReader sr = new StreamReader(url);
            string text = sr.ReadToEnd();
            sr.Close();//记得关闭流
            sr.Dispose();
            SaveData data = JsonMapper.ToObject<SaveData>(text);
            //GameManage.Instance.StartRestore(data);//自己写的还原数据的一个方法,不用管
        }
        else
        {
            Debug.LogError("当前读取的文件不存在" + url);
        }

    }

 写入方法:

    public void WriteJson(SaveData data)
    {
        try
        {
            string filePath = Application.dataPath + "/Resources/Data/" + data.sceneName + ".json";//不加后缀保存的不是json文件
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.Create(filePath).Dispose();//这里很重要,不dispose会报错
            StreamWriter sw = new StreamWriter(filePath);
            string json = JsonMapper.ToJson(data);
            sw.WriteLine(json);
            sw.Close();//记得关闭流
            sw.Dispose();
        }
        catch (Exception e)
        {
            DebugTool.Log(e.Message);
            throw;
        }
    }

注意,Resource文件夹打包的时候会进行压缩,打包后里面的文件是只能读取不能修改的,但是可以加载后修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值