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/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
最后更新于 ,距今已过 5 天
部分内容可能已过时