当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于Resources中的Json文件的读取

关于Resources中的Json文件的读取

2020年08月11日  | 移动技术网IT编程  | 我要评论
废话不多说,直接上代码,这里有几个注意点,看了几个文章都没提到,自己碰到了所以特别标注一下,其他内容别的博客都能找到。读取方法:方法1public void ReadJson(){ string url = "Data/" + GameManage.Instance.Scene.ToString();//注意,路径末尾不能加后缀,即不加.json,会报错 TextAsset text = Resources.Load<TextAsset>(url)

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

读取方法:

方法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();
            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;
        }
    }

本文地址:https://blog.csdn.net/qq_39936343/article/details/107911408

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网