[unity]对象的序列化

抽象的图纸叫类,包含具体数据的叫对象。

类的序列化和反序列化

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


using System;  
using System.IO;  
using System.Runtime.Serialization.Formatters.Binary;  
  

[Serializable]   
public class MyData  
{  
    public int Number { get; set; }  
    public string Text { get; set; }  
}  

public class Save : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        MyData data = new MyData() { Number = 123, Text = "Hello, world!" };  
  
        // 保存数据到硬盘  
        BinaryFormatter formatter = new BinaryFormatter();  
        using (FileStream stream = new FileStream("D://mydata.bin", FileMode.Create))  
        {  
            formatter.Serialize(stream, data);  
        }  
  
        // 从硬盘读取数据  
        MyData deserializedData;  
        using (FileStream stream = new FileStream("D://mydata.bin", FileMode.Open))  
        {  
            deserializedData = (MyData)formatter.Deserialize(stream);  
        }  
  
        Debug.Log(deserializedData.Number+" , "+deserializedData.Text);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


数组的序列化和反序列化

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 序列化和反序列化用到的
using System;  
using System.IO;  
using System.Runtime.Serialization.Formatters.Binary;  
  


public class Save : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // // 01.序列化
        // int[] intArray1 = { 1, 2, 3, 4, 5 };  
        // int[] intArray2 = { 10, 20, 30, 40, 50 };  
  
        // // 创建一个二进制格式化器  
        // BinaryFormatter formatter = new BinaryFormatter();  
  
        // // 创建一个文件流  
        // using (FileStream stream = new FileStream("D://test.bin", FileMode.Create))  
        // {  
        //     // 序列化第一个数组  
        //     formatter.Serialize(stream, intArray1);  
  
        //     // 序列化第二个数组  
        //     formatter.Serialize(stream, intArray2);  
        // }


        // 02.反序列化
        // 创建一个二进制格式化器  
        BinaryFormatter formatter = new BinaryFormatter();  
  
        // 创建一个文件流  
        using (FileStream stream = new FileStream("D://test.bin", FileMode.Open))  
        {  
            // 反序列化第一个数组  
            int[] intArray1 = (int[])formatter.Deserialize(stream);  
  
            // 反序列化第二个数组  
            int[] intArray2 = (int[])formatter.Deserialize(stream);  
  
            // 打印数组内容  
            foreach (int i in intArray1)  
            {  
                Debug.Log(i);  
            }  
  
            foreach (int i in intArray2)  
            {  
                Debug.Log(i);  
            }  
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


猜你喜欢

转载自blog.csdn.net/averagePerson/article/details/133442117