Protobuf-Net NotSupportedException:类型不能表示为封闭的不可变类型(UnityEngine.Vector3)的默认值

Dyl*_*nis 1 c# serialization protocol-buffers protobuf-net unity-game-engine

遵循有关如何使用protobuf-netProtobuf-net以及Unity3D类型序列化不可变的封闭类型的答案之后,我尝试实现可处理UnityEngine的Vector3容器的序列化程序,其中唯一重要的值是Vector3.x,Vector3。 y和Vector3.z:

使用以下TypeModel:

serializer = TypeModel.Create();
serializer.UseImplicitZeroDefaults = false;
Run Code Online (Sandbox Code Playgroud)

然后,我尝试了两种不同的方法,分别为Vector3添加协议定义。明确的定义:

serializer.Add(typeof(Vector3), false).Add(1, "x").Add(2, "y").Add(3, "z");
Run Code Online (Sandbox Code Playgroud)

并使用代理:

serializer.Add(typeof(Vector3), false).SetSurrogate(typeof(SurrogateVector3));
Run Code Online (Sandbox Code Playgroud)

与代理类:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用任何一种方法尝试序列化a时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)
...
Run Code Online (Sandbox Code Playgroud)

我不确定如何修改我的Typemodel或协议定义以成功序列化UnityEngine.Vector3的集合。

Mar*_*ell 5

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

[ProtoMap(DisableMap = true)]
Run Code Online (Sandbox Code Playgroud)

到作为字典的属性/字段。“地图”代码与原始“地图”之前代码之间的区别是微妙的,不是很有趣-它主要改变了重复情况下发生的事情-但是:“地图”中似乎有一个令人讨厌的错误逻辑,这可能在原始代码路径中不存在。但是,“地图”路径现在是默认路径,因此是禁用它的解决方法。