Unity 中XML序列化和反序列化
**序列化名词解释:序列化是将对象状态转换为可保持或传输的格式的过程。 XML序列化的实质: XML序列化过程的描述: XML反序列化的过程描述: 实际代码演示:序列化一个游戏物体(例如玩家,怪物,NPC等)对象的实例,可以将它的数据(例如:位置,名字,等级,血量,经验)序列化到XML中,,, using System;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
/// <summary>
/// 注意一定是公开的 需要序列化的玩家信息
/// </summary>
public class Player
{
public struct Pos
{
public float x,y,z;
}
public Pos pos;
public string name;
public float Exp;
public int Level;
public int HP;
}
public class SerializerDemo : MonoBehaviour {
private string path; //存储XML的路径
public Player p1; //获取玩家引用
// Use this for initialization
void Start () {
path = Application.dataPath + "/Demo.xml";
//实例化玩家,并初始化数据
p1 = new Player();
p1.name = "Czhenya";
p1.Exp = 0;
p1.Level = 0;
p1.HP = 0;
}
void OnGUI () {
if (GUILayout.Button("CreateXML"))
{
p1.pos.x = this.transform.position.x;
p1.pos.y = this.transform.position.y;
p1.pos.z = this.transform.position.z;
SerCreate();
}
if (GUILayout.Button("DeXML"))
{
DeSerCreate();
}
}
/// <summary>
/// 序列化方法
/// </summary>
private void SerCreate()
{
//指定流文件 (创建XML的目录)
FileInfo info = new FileInfo(path);
//Debug.Log(info);
StreamWriter sw; //流写入器对象,,
if (!info.Exists) //判断路径是否存在
{
//不存在创建
sw = info.CreateText();
}
else
{
//存在就删除,再创建
info.Delete();
sw = info.CreateText();
}
//实例化对象,并 指定序列化的类型
XmlSerializer ser = new XmlSerializer(typeof(Player));
//序列化方法,,(流写入器,玩家)
ser.Serialize(sw,p1);
sw.Close(); //关闭流
}
/// <summary>
/// 反序列化方法
/// </summary>
private void DeSerCreate()
{
//指定流文件
FileStream fs = new FileStream(path,FileMode.Open);
XmlSerializer xmlSer = new XmlSerializer(typeof(Player));
Player readp1 =(Player) xmlSer.Deserialize(fs);
Debug.Log(readp1.name); //得到的玩家信息
//将反序列化的信息赋值给玩家
this.transform.position = new Vector3(readp1.pos.x,readp1.pos.y,readp1.pos.z);
}
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |