概述
脚本必须放在Editor文件夹下才可以使用下面的引用,
using YamlDotNet.Serialization;
这个引用也是序列化所必须使用的;
代码如下:
using UnityEngine;
using System;
using UnityEditor;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using YamlDotNet.Serialization;
public class ItemInfo
{
private int id;
private string name;
public int ID
{
set{id = value;}
get{return id;}
}
public string Name
{
set{name = value;}
get{return name;}
}
}
public class TestInfo
{
private Rect m_position = new Rect();
private List<ItemInfo> listInfo = new List<ItemInfo>();
public float Xpos
{
get{return m_position.x;}
set{m_position.x = value;}
}
public float Ypos
{
get{return m_position.y;}
set{m_position.y = value;}
}
public float Width
{
get{return m_position.width;}
set{m_position.width = value;}
}
public float Height
{
get{return m_position.height;}
set{m_position.height = value;}
}
public List<ItemInfo> ListInfo
{
get{return listInfo;}
set{listInfo = value;}
}
}
public class SerializeObject {
string filePath = "D:/序列化数据/1.txt";
public static SerializeObject _instance = new SerializeObject();
[MenuItem("H3D/序列化")]
static void Init ()
{
_instance.Serializer ();
}
[MenuItem("H3D/反序列化")]
static void Init2 ()
{
_instance.Deserializer ();
}
void Serializer() // 序列化操作
{
object obj = GetSerializeObject();
StreamWriter yamlWriter = File.CreateText (filePath);
Serializer yamlSerializer = new Serializer();
yamlSerializer.Serialize(yamlWriter, obj);
yamlWriter.Close();
}
void Deserializer() // 反序列化操作
{
if (!File.Exists(filePath))
{
return;
}
StreamReader yamlReader = File.OpenText(filePath);
Deserializer yamlDeserializer = new Deserializer();
//读取持久化对象
TestInfo info = yamlDeserializer.Deserialize<TestInfo>(yamlReader);
yamlReader.Close();
PrintInfo (info);
}
public object GetSerializeObject() // 获得序列化的数据
{
TestInfo newInfo = new TestInfo();
newInfo.Xpos = 10;
newInfo.Ypos = 10;
newInfo.Width = 800;
newInfo.Height = 600;
List<ItemInfo> itemLists = new List<ItemInfo> ();
ItemInfo info1 = new ItemInfo ();
info1.ID = 1;
info1.Name = "aa";
itemLists.Add (info1);
ItemInfo info2 = new ItemInfo ();
info2.ID = 2;
info2.Name = "bb";
itemLists.Add (info2);
newInfo.ListInfo = itemLists;
return newInfo;
}
void PrintInfo(TestInfo info) // 输出序列化的数据
{
Debug.Log (info.Xpos);
Debug.Log (info.Ypos);
Debug.Log (info.Width);
Debug.Log (info.Height);
foreach (var item in info.ListInfo)
{
Debug.Log (item.ID);
Debug.Log (item.Name);
}
}
}
序列化后的效果图如下所示:
最后
以上就是俊逸老虎为你收集整理的Unity YAML 序列化与反序列化的全部内容,希望文章能够帮你解决Unity YAML 序列化与反序列化所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复