我正在尝试为名为Transform
的第三方类创建代理。我需要序列化它的一些公共成员,包括对另一个这样的类实例的引用,并公开内部列表Transforms
。所以我写了替代品,但我不确定是否可以在替代品的字段上定义[ProtoMember]
属性,该属性的类型为Transform
。或者他们应该是TransformSurrogate
?现在,我的代码是:代理类可以包含对原始类的引用
[ProtoContract(AsReferenceDefault = true)]
public class TransformSurrogate {
[ProtoMember(1)]
Vector3 localPosition { get; set; }
[ProtoMember(2)]
Vector3 localScale { get; set; }
[ProtoMember(3)]
Quaternion localRotation { get; set; }
[ProtoMember(4, AsReference = true)]
Transform parent { get; set; }
[ProtoMember(5, AsReference = true)]
List<Transform> children { get; set; }
public static explicit operator TransformSurrogate(Transform transform) {
if (transform == null) return null;
var surrogate = new TransformSurrogate();
surrogate.localPosition = transform.localPosition;
surrogate.localRotation = transform.localRotation;
surrogate.localScale = transform.localScale;
surrogate.parent = transform.parent;
surrogate.children = new List<Transform>();
for (int i = 0; i < transform.childCount; ++i) {
surrogate.children.Add(transform.GetChild(i));
}
return surrogate;
}
public static explicit operator Transform(TransformSurrogate surrogate) {
if (surrogate == null) return null;
var transform = new GameObject().transform;
transform.localPosition = surrogate.localPosition;
transform.localRotation = surrogate.localRotation;
transform.localScale = surrogate.localScale;
transform.parent = (Transform) surrogate.parent;
foreach (var child in surrogate.children) {
child.parent = transform;
}
return transform;
}
}
不要太注意Vector3
和Quaternion
班 - 他们很容易序列化的结构。所以我定义自己的RuntimeTypeModel
为Transform
类型是这样的:
Model.Add(typeof(Transform), false).SetSurrogate(typeof(TransformSurrogate));
不过,我反序列化过程中得到一个错误,告诉我的Protobuf是无法类之间的转换。我在想,这是因为在代理类中混合了原始类,但我不确定。
在一个依赖于非核心类型的复杂类型的环境中,这很难回答;你有没有用简单的本地类型演示问题的例子? – 2014-09-25 11:09:37
@MarcGravell现在我试图在更简单的环境中对这种情况建模,但是如果您想知道Vector3和Quaternion类型是什么 - 您可以跳过这些,因为它们是简单的结构,并且我已成功将它们序列化。我现在主要关注的只是Transform类。如果有帮助,Transform是Unity3D的内置类型。 – GuardianX 2014-09-25 12:24:31