1.实验的目的和要求
掌握序列化与反序列化的概念,掌握BinaryFormatter类,能够编写代码实现游戏对象的序列化与反序列化。
2.实验内容
在Unity脚本中,通过Serialize与Deserialize方法,实现游戏对象的序列化与反序列化。
3.主要代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class m : MonoBehaviour
{
private Hero heroInstance;
void Start()
{
heroInstance = new Hero();
heroInstance.id = 10000;
heroInstance.attack = 10000f;
heroInstance.defence = 90000f;
heroInstance.name = "lilei";
/*
Stream stream = InstanceDataToMemory(heroInstance);
stream.Position = 0;
heroInstance = null;
heroInstance = (Hero)this.MemoryToInstanceData(stream);
Debug.Log(heroInstance.id.ToString());
Debug.Log(heroInstance.attack.ToString());
Debug.Log(heroInstance.defence.ToString());
Debug.Log(heroInstance.name);
*/
}
void OnGUI()
{
if(GUILayout.Button("save(serialize)",GUILayout.Width(200))){
FileStream fs = new FileStream("HeroData.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, this.heroInstance);
}
catch(SerializationException e)
{
Console.WriteLine("Failed to Serialize.Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
this.heroInstance = null;
}
}
if (GUILayout.Button("Load(Deserialize)", GUILayout.Width(200)))
{
FileStream fs = new FileStream("HeroData.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
this.heroInstance = (Hero)formatter.Deserialize(fs);
}
catch(SerializationException e)
{
Console.WriteLine("Failed to Serialize.Reason:" + e.Message);
throw;
}
finally
{
fs.Close();
Debug.Log(heroInstance.id.ToString());
Debug.Log(heroInstance.attack.ToString());
Debug.Log(heroInstance.defence.ToString());
Debug.Log(heroInstance.name);
}
}
}
private MemoryStream InstanceDataToMemory(object instance)
{
MemoryStream memoStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoStream, instance);
return memoStream;
}
private object MemoryToInstanceData(Stream memoryStream)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
object Des_object = binaryFormatter.Deserialize(memoryStream);
return Des_object;
}
[Serializable]
class Hero
{
public int id;
public float attack;
public float defence;
public string name;
public Hero()
{
}
}
}
4.实验结果