Unity MessagePack代替Json让你的数据更小还更快
- 前言
- 项目
- 下载并安装MessagePack
- 编写测试代码
- 添加并设置脚本
- 生成AOT代码
- 编写加载AOT代码文件
- 运行效果
- 参考
前言
前端给后端发的Json数据有点大,使用MessagePack优化一下(MessagePack原理官网解释的很清晰),这里直接上用法。
项目
准备一个空项目
下载并安装MessagePack
到下面的地址下载.unitypackage
文件拖入Unity中
https://github.com/MessagePack-CSharp/MessagePack-CSharp/releases
拖入之后入下图
编写测试代码
创建MyClass.cs
并写入
using MessagePack;
[MessagePackObject]
public class MyClass
{
// Key attributes take a serialization index (or string name)
// The values must be unique and versioning has to be considered as well.
// Keys are described in later sections in more detail.
[Key(0)]
public int Age { get; set; }
[Key(1)]
public string FirstName { get; set; }
[Key(2)]
public string LastName { get; set; }
// All fields or properties that should not be serialized must be annotated with [IgnoreMember].
[IgnoreMember]
public string FullName { get { return FirstName + LastName; } }
}
创建Program .cs
并写入
using System.Collections;
using System.Collections.Generic;
using MessagePack;
using UnityEngine;
public class Program : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
var mc = new MyClass
{
Age = 99,
FirstName = "fn",
LastName = "ln",
};
// Call Serialize/Deserialize, that's all.
byte[] bytes = MessagePackSerializer.Serialize(mc);
MyClass mc2 = MessagePackSerializer.Deserialize<MyClass>(bytes);
// You can dump MessagePack binary blobs to human readable json.
// Using indexed keys (as opposed to string keys) will serialize to MessagePack arrays,
// hence property names are not available.
// [99,"hoge","huga"]
var json = MessagePackSerializer.ConvertToJson(bytes);
Debug.Log(json);
}
}
添加并设置脚本
将Program
挂载在场景中
生成AOT代码
打开CodeGenerator
窗口
写入项目路径和生成的代码路径,并点击Generate
按钮生成代码
生成的代码如下图
编写加载AOT代码文件
创建Startup.cs
并写入
如果使用
HybridCLR
热更方案,这里的方法建议拿到热更代码刚开始的地方,这里同样可以热更
using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;
public class Startup
{
static bool serializerRegistered = false;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Initialize()
{
if (!serializerRegistered)
{
StaticCompositeResolver.Instance.Register(
MessagePack.Resolvers.GeneratedResolver.Instance,
MessagePack.Resolvers.StandardResolver.Instance
);
var option = MessagePackSerializerOptions.Standard.WithResolver(StaticCompositeResolver.Instance);
MessagePackSerializer.DefaultOptions = option;
serializerRegistered = true;
}
}
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
static void EditorInitialize()
{
Initialize();
}
#endif
}
运行效果
可以看到能够正确序列化和反序列化类了。
参考
https://github.com/MessagePack-CSharp/MessagePack-CSharp#aot