【发布时间】:2016-09-30 23:37:38
【问题描述】:
我正在使用 JSON .NET 为我们的 Unity3D 游戏编写自定义序列化程序。我们可以有一些 GameObject 类型的字段,它是一个 Unity3D 内部类,将引用游戏中的资产资源。我们需要能够仅通过其 GUID 字符串序列化 GameObject 属性。使用这些信息,我们可以利用 Unity3D 的 AssetDatabase 检索资产并将其加载到属性中。
public class Blueprint {
public IList<IComponent> Components = new List<IComponent>();
}
public class UnityPrefabs : IComponent {
public GameObject ViewPrefab;
public GameObject ModelPrefab;
}
我使用 JSON .NET 序列化的方法:
public void Serialize(Blueprint blueprint) {
blueprintData = JsonConvert.SerializeObject(blueprint, Formatting.Indented,
new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
Converters = new List<JsonConverter>() { new UnityPrefabConverter() },
//ContractResolver = new ConverterContractResolver()
});
}
public Blueprint Deserialize() {
var blueprint = string.IsNullOrEmpty(blueprintData)
? new Blueprint() : JsonConvert.DeserializeObject<Blueprint>(blueprintData,
new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
//TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
NullValueHandling = NullValueHandling.Include,
Converters = new List<JsonConverter>() { new UnityPrefabConverter() },
});
return blueprint;
}
我确实尝试编写一个自定义转换器,但是没有调用 Write() 方法,而只有 Read() 是:
public class UnityPrefabConverter : JsonConverter {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var go = value as GameObject;
var guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(go));
writer.WriteValue(guid);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Debug.Log("Reading json");
if (existingValue == null) return null;
return AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GUIDToAssetPath(existingValue as string));
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(GameObject));
}
}
我现在唯一能找到的奇怪之处是它没有序列化 JSON 中 GameObject 字段的类型:
{\r\n \"$type\": \"CubeBasic.Model.UnityPrefabs, Assembly-CSharp\",\r\n
\ \"ViewPrefab\": \"\",\r\n \"ModelPrefab\": null\r\n }\r\n
\ ]\r\n }\r\n}"
【问题讨论】: