什么是序列化,反序列化?
序列化就是把数据对象转换成二进制流保存为本地文件的过程。
反序列化就是把储存有数据信息的二进制文件还原成数据对象的过程。
序列化的意义
以某种储存形式(二进制/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