【问题标题】:How can I custom serialize a GameObject reference by its GUID?如何通过 GUID 自定义序列化 GameObject 引用?
【发布时间】: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}"

【问题讨论】:

    标签: c# unity3d json.net


    【解决方案1】:

    没有调用您的转换器,因为在序列化期间,objectType 是被序列化的GameObject 的实际类型,因此是GameObject 的子类型。修改CanConvert使用Type.IsAssignableFrom(Type):

    public override bool CanConvert(Type objectType)
    {
        return typeof(GameObject).IsAssignableFrom(objectType);
    }
    

    另外,在您的ReadJson 中,您可能不想检查existingValue 是否为空,而是您想做:

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        Debug.Log("Reading json");
        if (reader.TokenType == JsonToken.Null)
            return null;
        var guid = (string)JToken.Load(reader); // Load the GUID value
    
        return AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GUIDToAssetPath(guid));
    }
    

    existingValue 是对在构造函数中为包含对象预分配的任何 POCO 的引用。

    由于您已经为GameObject 编写了自己的JsonConverter,因此除非您在转换器中明确这样做,否则不会编写object types。但是,由于您实际上并没有反序列化对象,而只是从某个数据库中获取它,所以我认为没有必要。

    【讨论】:

    • 注意 - 我不是统一开发人员,所以可能会有其他问题。
    • 不,那太好了。发挥了魅力。
    【解决方案2】:

    你应该试试 Newtonsoft(你可以将它作为 Nuget 包添加到你的项目中),你可以编写一个通用的 JSonSerializer 类

    using Newtonsoft.Json;
    
    public class JSonSerializer : IObjectSerializer
    {
        public string ToJson<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
    
        public T FromJson<T>(string json)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch(JsonReaderException e)
            {
                throw new ObjectSerializationException(e);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2019-10-07
      • 2011-04-30
      • 1970-01-01
      • 2015-10-25
      • 2022-10-08
      • 1970-01-01
      相关资源
      最近更新 更多