美文网首页
序列化和反序列化(Serialize)

序列化和反序列化(Serialize)

作者: 道阻且长_行则将至 | 来源:发表于2017-10-21 23:40 被阅读24次

将一个对象序列化和反序列化的代码(亲测可用,多个对象可以序列化到一个文件中并且在反序列化时互不影响):

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();
        }
    }
}

相关文章

网友评论

      本文标题:序列化和反序列化(Serialize)

      本文链接:https://www.haomeiwen.com/subject/bmgwuxtx.html