Unity3d Json 读写文件

来源:互联网 发布:淘宝客怎么设置单品 编辑:程序博客网 时间:2024/05/16 18:08

Unity3d 中使用Json读取文件
需要导入 LitJson.dll的动态链接库,然后再代码里使用命名空间
调用

using System.Collections;using System.Collections.Generic;using System.IO;using UnityEngine;using LitJson;public class PlayerInfo{    public PlayerInfo()    {        name="default";        level=0;    }    string name;    int level;}public classPlayerCtrl:MonoBehaviour{    string path=Application.dataPath+"/playerInfo.json";    void Start()    {        Save(path);        Load(path);    }    //根据路径读取数据并且用Json解析    void Load(string path)    {        string[] strs=File.ReadAllLines(path);        List<PlayerInfo> allInfo=new List<PlayerInfo>();        foreash(string str in strs)        {            PlayerInfo info=JsonMapper.ToObject<PlayerInfo>(str);            allInfo.Add(info);        }       }    void Save(string path)    {        List<string> pInfos;        //存储操作,先判断路径下面是否有文件        //——如果有,就在文件内的数据追加数据        //——如果没有,就在路径下创建出一个想要的文件,并进行存储        if(File.Exists(path))        {            string[] allInfo=File.ReadAllLines(path);            pInfos=new List<string>(allInfo);        }        else        {            allInfo=new List<string>();        }        PlayerInfo info=new PlayerInfo();//初始化玩家信息        //此处可以进行一些玩家数据处理的操作        string nowInfo=JsonMapper.ToJson(info);        allInfo.Add(nowInfo);        File.WriteAllLines(path,allInfo.ToArray());//将数据存储到路径下    }}

以上为今天掌握内容

原创粉丝点击