-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityScriptableObjectSerializer.cs
More file actions
78 lines (66 loc) · 2.11 KB
/
UnityScriptableObjectSerializer.cs
File metadata and controls
78 lines (66 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
// most sane json serializer in unity here
public class UnityScriptableObjectSerializer : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var scriptableObject = value as ScriptableObject;
if (scriptableObject == null)
{
writer.WriteNull();
return;
}
string json = JsonUtility.ToJson(scriptableObject);
var jObject = JObject.Parse(json);
RemoveFieldsWithInstanceID(jObject);
jObject.WriteTo(writer);
}
private void RemoveFieldsWithInstanceID(JToken token)
{
var tokensToRemove = new List<JToken>();
CollectTokensToRemove(token, tokensToRemove);
foreach (var tok in tokensToRemove)
{
tok.Remove();
}
}
private void CollectTokensToRemove(JToken token, List<JToken> tokensToRemove)
{
if (token.Type == JTokenType.Object)
{
var children = token.Children<JProperty>().ToList();
foreach (var child in children)
{
if (child.Value is JObject childObject && childObject["instanceID"] != null)
{
tokensToRemove.Add(child);
}
else
{
CollectTokensToRemove(child.Value, tokensToRemove);
}
}
}
else if (token.Type == JTokenType.Array)
{
foreach (var child in token.Children())
{
CollectTokensToRemove(child, tokensToRemove);
}
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var json = JToken.Load(reader).ToString();
return JsonUtility.FromJson(json, objectType);
}
public override bool CanConvert(Type objectType)
{
return typeof(ScriptableObject).IsAssignableFrom(objectType);
}
}