Unity2019.4通过NuGetForUnity装protobuf-net报System.Buffers加载失败如何修复
Unity 2019.4 环境下protobuf-net 类型加载异常修复
触发的异常信息
执行序列化流程时触发以下TypeLoadException错误:
TypeLoadException: Could not load type of field 'ProtoBuf.BufferPool:_pool' (0) due to: Could not load file or assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. ProtoBuf.ProtoWriter+StreamProtoWriter.CreateStreamProtoWriter (System.IO.Stream dest, ProtoBuf.Meta.TypeModel model, System.Object userState) ProtoBuf.ProtoWriter+State.Create (System.IO.Stream dest, ProtoBuf.Meta.TypeModel model, System.Object userState) ProtoBuf.Serializer.Serialize[T] (System.IO.Stream destination, T instance, System.Object userState) ProtoBuf.Serializer.Serialize[T] (System.IO.Stream destination, T instance) ProtobufNetTest.Awake () (at Assets/Tests/Protobuf-net/ProtobufNetTest.cs:26)
问题根源
测试脚本为标准的protobuf-net序列化逻辑,不存在语法层面问题,报错来自依赖链路不匹配:通过NuGetForUnity安装的protobuf-net版本,强依赖System.Buffers 4.0.2.0版本程序集,而Unity 2019.4内置的.NET运行时自带的同类程序集版本低于要求值;NuGetForUnity在导入包时没有自动把缺失的依赖链路同步到Unity工程的插件目录,最终导致程序集加载、类型初始化失败。
修复操作步骤
- 清理旧残留版本:打开NuGetForUnity管理面板,卸载当前安装的protobuf-net包,删除
Assets/Plugins目录下所有和protobuf-net、System.Buffers、System.Memory相关的旧dll文件,避免多版本dll共存引发冲突。 - 导入匹配版本的程序集:选择适配Unity 2019.4运行时的protobuf-net 3.0.x兼容版本,同时把和该protobuf-net版本配对的三个依赖dll(
System.Buffers.dll 4.0.2.0、System.Memory.dll、System.Runtime.CompilerServices.Unsafe.dll)放到Assets/Plugins目录下,所有dll的平台导入设置勾选“任何平台”,不要针对特定编译环境做裁剪。 - 配置程序集重定向:在
Assets/Plugins目录下新建mcs.rsp配置文件,添加版本绑定规则解决Unity内置程序集和导入依赖的版本冲突,文件内容为:--redef:System.Buffers,Version=4.0.2.0,Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51 - 重启验证:重启Unity编辑器完成编译,运行测试脚本,能够在控制台输出
Round tripped: 313373日志即代表流程正常。
避坑提示
注意:不要直接安装protobuf-net 3.2及以上的最新主版本,这类版本针对.NET 6+运行时设计,对Unity 2019.x内置的.NET Standard 2.0兼容支持很差,会持续触发各类类型加载异常。如果不想手动配置依赖,也可以选择社区预编译的Unity适配版protobuf-net包,省去手动处理依赖的步骤。
内容的提问来源于stack exchange,提问作者Eddie Parker
相关产品推荐
相关产品推荐

