将一个对象序列化和反序列化的代码(亲测可用,多个对象可以序列化到一个文件中并且在反序列化时互不影响):
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class Seralize : MonoBehaviour {
public void Xuliehua(){
Hero hero = new Hero("Hero",100,30);
FileStream fs = new FileStream("Assets/HeroData.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, hero);
Debug.Log("序列化成功!");
}
catch(SerializationException e)
{
Debug.Log("ERROR01 :"+e.Message);
}finally
{
fs.Close();
hero = null;
}
}
public void Fanxuliehua()
{
FileStream fs = new FileStream("Assets/HeroData.dat", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
try
{
Hero hero = (Hero)formatter.Deserialize(fs);
Debug.Log("反序列化成功!");
Debug.Log("这个对象是 :"+ hero.name + " " + hero.hp + " " + hero.atk);
}
catch (SerializationException e)
{
Debug.Log("ERROR02 :" + e.Message);
}
finally
{
fs.Close();
}
}
}
网友评论