using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class MyHero
{
//记住序列化的类 一定要加 标签:Serializable 不然会报错
public string Heroname;
public int ID;
public int HP;
public int Atk;
public int Def;
}
public class SerializedTest : MonoBehaviour {
void Start () {
MyHero myHero = new MyHero
{
Heroname = "Ranner",
ID = 333,
HP = 10000,
Atk = 1003,
Def = 1009
};
//进行序列化
Stream stream = InstanceDataForMemory(myHero);
stream.Position = 0;
myHero = null; //清空这里的 hero 的数据
myHero = MemoryToInstanceData(stream) as MyHero;
Debug.Log(myHero.Heroname);
Debug.Log(myHero.ID);
Debug.Log(myHero.HP);
Debug.Log(myHero.Atk);
}
/// <summary>
/// 序列化方法
/// </summary>
/// <param name="obj"></param>
private MemoryStream InstanceDataForMemory(object obj)
{
//创建一个新的流来 存储容纳 经过序列化的对象
MemoryStream memoryStream = new MemoryStream();
//创建一个格式化器 来执行具体的序列化操作
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream;
}
/// <summary>
/// 反序列化方法
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
private object MemoryToInstanceData(Stream stream)
{
//创建一个反序列化各时期,来执行操作
BinaryFormatter binaryFormatter = new BinaryFormatter();
return binaryFormatter.Deserialize(stream);
}
}