最近工作需要用到数据持久化,所以在此分享一下,通过查阅资料,数据持久化大体都是通过xml或者json来进行的。unity为我们自定义了数据持久化方法,但是比较局限,还需要自己来完成数据持久化方法。

(一)unity方法

unity提供了三个方法来实现数据持久化,不过只能对int float string类型进行数据持久化,命令如下

        //设定Key=float的值为12f
PlayerPrefs.SetFloat("float", 12f);
//通过key值“float”获取数值12,如果“float”未设定值,则默认为1f
PlayerPrefs.GetFloat("float", 1f);
//相关定义与setfloat相同
PlayerPrefs.SetInt("int", );
PlayerPrefs.GetInt("int", );
PlayerPrefs.SetString("str", "abc");
PlayerPrefs.GetString("str", "default");

unity提供的方法比较局限,复杂数据还需要自己进行数据可持续化

(二)C#与xml

通过C#编写读取修改xml

1)编写xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO; namespace MenuData
{
class Program
{
static void Main(string[] args)
{
string filePath = "";
string fileName = "MenuData.xml";
string targetFile = Path.Combine(filePath, fileName); string[] mainMenu = new string[]{
"文件","配置","显示","诊断","投入运行","关机","帮助"};
string[] parentMenu = new string[]
{
"投入运行助手","测量","调整","软件更新","售后服务","机器人数据","网络配置","辅助软件"
}; string[] childMenu = new string[]
{
"工具","基坐标","固定工具","附加负载数据","外部运动装置","测量点","允差"
};
string[] toolMenu = new string[]
{
"XYZ_4点法","XTZ_参照法","ABC_2点法","ABC_世界坐标系","数字输入","更改名称","工具负荷数据"
};
string[] baseMenu = new string[]
{
"_3点法","间接","数字输入","更改名称"
};
XmlDocument xmldoc = new XmlDocument();
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
xmldoc.AppendChild(xmldecl); XmlElement menu = xmldoc.CreateElement("", "Menu", "");
xmldoc.AppendChild(menu); //XmlNode root = xmldoc.SelectSingleNode("Menu");//查找<menu>
for (int i = ; i < mainMenu.Length; i++)
{
XmlElement rootElem = xmldoc.CreateElement(mainMenu[i]);//创建一个<mainMenu[i]>节点
rootElem.SetAttribute("Layer", "");//设置该节点ID属性
if (i == )
{
for (int j = ; j < parentMenu.Length; j++)
{
XmlElement parentElem = xmldoc.CreateElement(parentMenu[j]);//创建一个<parentElem[i]>节点
parentElem.SetAttribute("Layer", "");//设置该节点ID属性
if (j == )
{
for (int m = ; m < childMenu.Length; m++)
{
XmlElement childElem = xmldoc.CreateElement(childMenu[m]);//创建一个<childMenu[i]>节点
childElem.SetAttribute("Layer", "");
if (m == )
{
for (int ii = ; ii < toolMenu.Length; ii++)
{
XmlElement elem = xmldoc.CreateElement(toolMenu[ii]);//创建一个<childMenu[i]>节点
elem.SetAttribute("Layer", "");
// elem.InnerText = toolMenu[ii];
childElem.AppendChild(elem);
}
}
if (m == )
{
for (int ii = ; ii < baseMenu.Length; ii++)
{
XmlElement elem = xmldoc.CreateElement(baseMenu[ii]);//创建一个<childMenu[i]>节点
elem.SetAttribute("Layer", ""); // elem.SetAttribute("type", "noChild");
//elem.InnerText = baseMenu[ii];
childElem.AppendChild(elem);
}
}
parentElem.AppendChild(childElem);
}
}
rootElem.AppendChild(parentElem);
}
} menu.AppendChild(rootElem);
}
xmldoc.Save(targetFile);
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; namespace XmlRW
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmldoc = new XmlDocument();
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
xmldoc.AppendChild(xmldecl); //加入一个根元素
XmlElement xmlelem = xmldoc.CreateElement("", "ToolAndFrame", "");
xmldoc.AppendChild(xmlelem); for (int i = ; i < ; i++)
{
string identifyStr;
string id;
int count;
if(i==)
{
identifyStr = "tool";
count = ;
}
else
{
identifyStr = "frame";
count = ;
}
//增加次级节点
XmlNode root = xmldoc.SelectSingleNode("ToolAndFrame");//查找<ToolAndFrame>
XmlElement elem = xmldoc.CreateElement(identifyStr);//创建一个<identifyStr>节点
elem.SetAttribute("ID", identifyStr);//设置该节点ID属性
//xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性 for(int j=;j<count;j++)
{
XmlElement toolElem = xmldoc.CreateElement("elem"+i.ToString());
toolElem.SetAttribute("ID", j.ToString());
toolElem.InnerText = "未知 [?]";
elem.AppendChild(toolElem);
} root.AppendChild(elem);//添加到<Employees>节点中
}
xmldoc.Save("ToolAndFrame.xml");
}
}
}

2)读取

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; namespace ReadXml
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("ToolAndFrame.xml");
List<string> strList = new List<string>();
XmlNodeList nodeList = xmlDoc.SelectSingleNode("ToolAndFrame").ChildNodes;//获取Employees节点的所有子节点 foreach (XmlNode temp in nodeList)//遍历所有子节点
{
XmlElement elem = (XmlElement)temp;//将子节点类型转换为XmlElement类型
//if (elem.GetAttribute("genre") == "张三")//如果genre属性值为“张三”
//{
// elem.SetAttribute("genre", "update张三");//则修改该属性为“update张三”
//}
XmlNodeList childElem = elem.ChildNodes;//继续获取xe子节点的所有子节点
foreach (XmlNode node in childElem)//遍历
{
XmlElement xml = (XmlElement)node;//转换类型
//if (xml.Name == "author")//如果找到
//{
// xml.InnerText = "亚胜";//则修改
//}
strList.Add(xml.InnerText);
}
} foreach(string str in strList)
{
Console.WriteLine(str);
}
Console.WriteLine(strList.Count);
Console.ReadKey();
}
}
}

3)查找与更改

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; namespace ChangeText
{
class Program
{
static void Main(string[] args)
{
string id = "tool";
int num = ;
string text = "new Name";
ChangeVal(id, num, text);
}
public static void ChangeVal(string id,int num,string text)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("ToolAndFrame.xml");
// List<string> strList = new List<string>();
XmlNodeList nodeList = xmlDoc.SelectSingleNode("ToolAndFrame").ChildNodes;//获取Employees节点的所有子节点 foreach (XmlNode temp in nodeList)//遍历所有子节点
{
XmlElement elem = (XmlElement)temp;//将子节点类型转换为XmlElement类型
if (elem.Name == id)//如果elem的名字为“张三”
{
Console.WriteLine(elem.GetAttribute("ID"));
Console.WriteLine(elem.Name); XmlNodeList childElem = elem.ChildNodes;//继续获取xe子节点的所有子节点
foreach (XmlNode node in childElem)//遍历
{
XmlElement xml = (XmlElement)node;//转换类型
if (xml.GetAttribute("ID") == num.ToString())
{
xml.InnerText = text;
break;
}
}
break;
}
}
xmlDoc.Save("ToolAndFrame.xml");
Console.ReadKey();
}
}
}

本文查找与更改只是更改了属性,如果需要添加节点或者删除节点,只需要查找到相关节点以后,用命令remvoechild即可,最后一定要保存。

(三)json

如果采用json格式实现数据可持续化则可以直接采用unity方法jsonUtility来实现

    private string WriteTOJson()
{
string json = JsonUtility.ToJson(jsonData);
return json;
}
private PersistData ReadFromJson(string json)
{
PersistData jsonClass = JsonUtility.FromJson<PersistData>(json);
return jsonClass;
}
    class PersistData
{
public long width;
public long top;
public long left;
public long height;
}

对于list格式的参数进行解析时要增加serializable

如下所示:

#region jsonClass
[Serializable]
public class ListModel
{
public int ListContentId;
public string CName;//新版本
public string EName;//新版本
//public string Name;//旧版本
public string BigResourcePath;
public string BigResourceName;
public string BigResourceType;
public string SmallResourcePath;
public string SmallResourceName;
public string SmallResourceType;
public DateTime UpdateTime;
public int Order;
public int Level;
public int ParentId; //public int ListContentId;
//public string Name;
//public string BigResourcePath;
//public string BigResourceName;
//public string BigResourceType;
//public string SmallResourcePath;
//public string SmallResourceName;
//public string SmallResourceType;
//public DateTime UpdateTime;
//public int Order;
//public int Level;
//public int ParentID;
}
[Serializable]
public class ListLevelModel
{
public bool success; public List<ListModel> data;
} #endregion
listLevelModel = JsonUtility.FromJson<ListLevelModel>(jsonlist);  

(四)LitJson

采用unity自带的解析方法时,在解析list时需要构筑一个带list的类,不能直接解析成list,而litjson可以如:

allComments = JsonMapper.ToObject<List<CommentElem>>(json);

也可以直接解析出所需要的参数,如下所示,可以直接获取到det下add的值

 JsonData data = JsonMapper.ToObject(json);

string str = data["Det"]["add"]

PS:如果xml需要跳过注释可用

            if(temp is XmlComment)
{
continue;
}

Unity C#数据持久化与xml的更多相关文章

  1. unity 初始化数据存储问题

    在用unity进行开发的时初始化的数据和中间实时生成的数据存储不同,初始化文件数据建议安放在asset-StreamingAssets文件下,需要时读取取来.运行时所需的实时文件或数据持久化的xml文 ...

  2. IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)

    IOS学习:ios中的数据持久化初级(文件.xml.json.sqlite.CoreData) 分类: ios开发学习2013-05-30 10:03 2316人阅读 评论(2) 收藏 举报 iOSX ...

  3. Unity 自定义Inspector面板时的数据持久化问题

    自定义Inspector面板的步骤: Unity内创建自定义的Inspector需要在Asset的任意文件夹下创建一个名字是Editor的文件夹,随后这个文件夹内的cs文件就会被放在vstu生成的Ed ...

  4. iOS之数据持久化方案

    概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) ...

  5. iOS的数据持久化

    所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) pr ...

  6. iOS开发备忘录:属性列表文件数据持久化

    属性列表文件是一种XML文件,Foundation框架中的数组和字典等都可以于属性列表文件相互转换. NSArray类常用读写属性列表文件的方法: +arrayWithContentsOfFile:类 ...

  7. 数据持久化(一)--NSKeyedArchiver

    数据持久化:  将内存中的数据按某种格式存进磁盘 数据的种类: 1,结构化的数据 2, 字节流数据 结构化的数据        字节流 内存中结构化的数据   ->   磁盘,  叫: 归档 字 ...

  8. 几种.NET平台数据持久化框架介绍

    原文连接:http://yuxnet.blog.163.com/blog/static/164863495201131532223362/ 在.NET平台下,关于数据持久层框架非常多,本文主要对如下几 ...

  9. iOS数据持久化-OC

    沙盒详解 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...

随机推荐

  1. Robot Framework自定义测试库的作用域的理解

    robot framework中,强大的测试库api支持,用户可根据实际需求定义测试库,导入后可使用自定义库中相应的关键字. 当自定义的测试库是类库,则需要考虑一个问题:类实例.用类实现的库可以有内部 ...

  2. Spring框架(三)

    对象依赖关系 Spring中,如何给对象的属性赋值?  [DI, 依赖注入] 1) 通过构造函数 2) 通过set方法给属性注入值 3) p名称空间 4)自动装配(了解) 5) 注解 代码示例: &l ...

  3. 【转+】python为什么推荐使用多进程

    最近在看Python的多线程,经常我们会听到老手说:“Python下多线程是鸡肋,推荐使用多进程!”,但是为什么这么说呢?                要知其然,更要知其所以然.所以有了下面的深入研 ...

  4. vue使用readAsDataURL实现选择图片文件后预览

    vue实现选择图片文件后预览 利用h5的api可以实现选择文件并实现预览 readAsDataURL 方法会读取指定的 Blob 或 File 对象.读取操作完成的时候,readyState 会变成已 ...

  5. phaser学习总结之phaser入门教程

    前言 最近公司做项目的时候正好使用到phaser,在这里做一下自己整理出来的一些心得,方便大家参考,phaser这一个游戏引擎通常是做2d游戏的,入门也非常简单,只需你会一点的javascript,但 ...

  6. java基础之缓存:session、cookie和cache的区别

    以前实现数据的缓存有很多种方法,有客户端的Cookie,有服务器端的Session和Application. 其中Cookie是保存在客户端的一组数据,主要用来保存用户名等个人信息. Session则 ...

  7. python pytesseracct WinError2

    接上一个3步图像识别,本来已经在两台电脑同样的操作3步都可以识别出验证码,但是今天在新电脑同样的步骤却出现了winerror2,泪崩. 一样的配方,不一样的结果. 后来发现是调用不到tesseract ...

  8. Ned 的难题

    题目描述 Ned 再也看不下去 Robert 的种种恶习, 于是他决定出一道题来让他醒悟. Ned 的题目是这样: 给出一个有 n 个数的序列, 求其中所有连续子序列的数的最大公因数的乘积模 1000 ...

  9. Oracle数据库实验一建立数据库

    实验日期:   2019 年  09 月  24  日 实验报告日期:   2019  年  09 月  28 日 一.      实验目的 熟悉oracle环境: 熟练掌握和使用PL-SQL建立数据 ...

  10. 使用jmeter进行压力测试入门讲解

    1.下载安装jmeter 略 我这里放上5.1版本的,有需要可以下载 链接:https://pan.baidu.com/s/1xRZZmTY4do1oDU_xPit94Q&shfl=share ...