212 字
1 分钟
Unity 二进制序列化:BinaryFormatter

两个核心 API#

API干什么相当于 JSON 里的
bf.Serialize(stream, obj)对象 → 2进制,写进流JsonUtility.ToJson
bf.Deserialize(stream)从流读回 object(要 as 转型)JsonUtility.FromJson<T>

用法一:存文件 / 读文件(配 FileStream)#

csharp

// 存档:对象 → 文件
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, p);
fs.Flush();
fs.Close();
}
// 读档:文件 → 对象
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
{
BinaryFormatter bf = new BinaryFormatter();
Person p = bf.Deserialize(fs) as Person;
fs.Close();
}

用法二:字节数组 ↔ 对象(配 MemoryStream,网络传输场景)#

csharp

// 对象 → 字节数组
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, p);
byte[] bytes = ms.ToArray(); // GetBuffer() 也行,但带 0 填充
}
// 字节数组 → 对象
using (MemoryStream ms = new MemoryStream(bytes))
{
BinaryFormatter bf = new BinaryFormatter();
Person p = bf.Deserialize(ms) as Person;
}

踩坑#

  • 嵌套类型没加 [System.Serializable] → SerializationException
  • GetBuffer() 带 0 填充,要精确字节数用 ToArray()
  • Deserialize 返回 object,忘了 as 编译不过。
Unity 二进制序列化:BinaryFormatter
https://jinshuangyan.top/posts/unity-binaryformatter/
作者
烬霜言
发布于
2026-10-06
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类