unity五种数据储存方法——序列化和反序列化

什么是序列化,反序列化?

序列化就是把数据对象转换成二进制流保存为本地文件的过程。
反序列化就是把储存有数据信息的二进制文件还原成数据对象的过程。

序列化的意义

以某种储存形式(二进制/XML,今天只讲二进制方法)使自定义对象持久化
方便将对象从一个地方移动到另一个地方(转移文件再反序列化读取)
使游戏数据不容易被直接篡改

序列化在unity中的注意点
不可以直接序列化unity特有的数据类型(例如Vector3, Quaternion),必须要转换一下(例子在下)。不然会报错:“SerializationException: Type UnityEngine.XXX is not marked as Serializable.”

举个例子

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Runtime.Serialization.Formatters.Binary;//实现二进制串行化必需的库
using System;
using System.IO;//实现文件流所必需的库
using UnityEngine.UI;


[Serializable]   //这里指下面的PlayerData可以被序列化
public class PlayerData
{
    public int size;
}
    
public class ui_stroage : MonoBehaviour
{
    Text input;
    InputField fontSizevalue;

    string getintvalue;
    int adc;
    public void inputfontsize()
    {
        fontSizevalue = GameObject.Find("Canvas/sizeinput").GetComponent<InputField>();
        print("标签为:" + fontSizevalue.text);
        getintvalue=fontSizevalue.text;
    }
    
    public void Getintbutton()
    {
        
        adc=int.Parse(getintvalue);
        Debug.Log(getintvalue);
        Debug.Log(adc);

    }
    public int currentsize =0;
    // Start is called before the first frame update
    void Start()
    {
        
    }


    
    public void SaveSystem()
    { 
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file= File.Create(Application.persistentDataPath + "/aaaa.dat");
        PlayerData data = new PlayerData();
        // data.size=adc;
        data.size=100;
        Debug.Log(data.size);
        bf.Serialize(file,data);
        file.Close();
        GameObject.Find("Canvas/TextA").GetComponent<Text>().fontSize=data.size;
    }
    public void LoadSystem()
    {
        
        if (File.Exists(Application.persistentDataPath + "/aaaa.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/aaaa.dat",FileMode.Open);
            PlayerData data = bf.Deserialize(file) as PlayerData;
            file.Close();
            currentsize = data.size;
            Debug.Log(currentsize);
            GameObject.Find("Canvas/TextA").GetComponent<Text>().fontSize=currentsize;
        }else
        {
            Debug.Log("No file");
        }
    }



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


作者:JervieQin
链接:https://www.jianshu.com/p/a67f11ec7cf1

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值