c# - Protobuf-Net NotSupportedException : Type cannot be represented as a default value for closed immutable type (UnityEngine. 矢量3)

标签 c# unity-game-engine serialization protocol-buffers protobuf-net

遵循How to serialize a closed immutable type with protobuf-net的答案和 Protobuf-net and Unity3D types ,我尝试实现一个可以处理 UnityEngine 的 Vector3 容器的序列化器,其中唯一重要的值是 Vector3.x、Vector3.y 和 Vector3.z:

使用以下类型模型:

serializer = TypeModel.Create();
serializer.UseImplicitZeroDefaults = false;

然后我分别尝试了两种不同的方法来为 Vector3 添加协议(protocol)定义;明确的定义:

serializer.Add(typeof(Vector3), false).Add(1, "x").Add(2, "y").Add(3, "z");

并使用代理:

serializer.Add(typeof(Vector3), false).SetSurrogate(typeof(SurrogateVector3));

具有代理类:

[ProtoContract]
public sealed class SurrogateVector3
{
    [ProtoMember(1)]
    float x; 
    [ProtoMember(2)]
    float y; 
    [ProtoMember(3)]
    float z;

    public SurrogateVector3()
    {}

    public SurrogateVector3(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static implicit operator Vector3(SurrogateVector3 v)
    {
        return new Vector3(v.x, v.y, v.z);
    }

    public static implicit operator SurrogateVector3(Vector3 v)
    {
        return new SurrogateVector3(v.x, v.y, v.z);
    }
}

当使用任一方法尝试序列化 Dictionary<int, Vector3> 时,抛出以下异常:

NotSupportedException: Type cannot be represented as a default value: UnityEngine.Vector3
ProtoBuf.Serializers.DefaultValueDecorator.EmitBranchIfDefaultValue (ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.CodeLabel label) (at <5e93d5bf6f2048709aab19aea88deb74>:0)
...

我不确定如何修改我的类型模型或协议(protocol)定义以便成功序列化 UnityEngine.Vector3 集合。

最佳答案

这可能是“ map ”代码中的一个错误,需要修复。您现在可以通过添加以下内容来避免它:

[ProtoMap(DisableMap = true)]

到作为字典的属性/字段。 “ map ”代码和原始的“ map ”之前的代码之间的区别很微妙,而且不是很有趣 - 它主要改变了重复情况下发生的情况 - 但是:“ map ”中似乎有一个恼人的错误从逻辑上看,原始代码路径中可能不存在。但是,“ map ”路径现在是默认路径,因此可以采取禁用它的解决方法。

关于c# - Protobuf-Net NotSupportedException : Type cannot be represented as a default value for closed immutable type (UnityEngine. 矢量3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639757/

相关文章:

java - 在 Storm 拓扑中出现 NotSerializedException 错误

c# - 创建安装程序包 Visual Studio 2010

c# - 强制 HttpWebRequest 使用 HTTP 1.0 并在 Windows 8 的 PCL 中设置 UserAgent

html - UnityScript 音频问题

unity-game-engine - C++ dll 的 unity3d 插件中的 DllNotFoundException

java - 可序列化对象的组合也可序列化吗?

c# - 在 C# 中加速矩阵加法

c# - 为什么 BitConverter 在转换 float 和字节时似乎返回不正确的结果?

c# - 是否有必要在 Unity 中开发多种屏幕分辨率?

java - 使用 gson 在 Java 中序列化千兆字节的 python 对象