-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathAutoSetPostprocessor.cs
245 lines (220 loc) · 9.51 KB
/
AutoSetPostprocessor.cs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright (c) Meta Platforms, Inc. and affiliates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using GetComponentFunc = System.Func<UnityEngine.Component, object>;
namespace Meta.Utilities.Editor
{
internal class AutoSetPostprocessor : AssetPostprocessor
{
private static IEnumerable<Scene> GetActiveScenes()
{
for (var i = 0; i != SceneManager.sceneCount; i += 1)
yield return SceneManager.GetSceneAt(i);
}
private static void OnPostprocessAllAssets(string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
var assets = importedAssets.Select(AssetDatabase.LoadAssetAtPath<UnityEngine.Object>);
foreach (var gameObject in assets.OfType<GameObject>().OrderBy(GetPrefabDepth))
{
CheckPrefab(gameObject);
}
foreach (var (path, asset) in importedAssets.Zip(assets))
{
if (asset is SceneAsset sceneAsset)
{
CheckScene(path);
}
}
}
private static int GetPrefabDepth(GameObject obj)
{
return 1 + obj.GetComponentsInChildren<Transform>(true).
Select(PrefabUtility.GetCorrespondingObjectFromSource).
Where(source => source != null).
Concat(new[] { null as Transform }).
Max(source => source == null ? 0 : GetPrefabDepth(source.gameObject));
}
private static void CheckPrefab(GameObject gameObject)
{
if (CheckObjects(new[] { gameObject }))
{
_ = PrefabUtility.SavePrefabAsset(gameObject);
}
}
private static void CheckScene(string path)
{
var scene = GetActiveScenes().FirstOrDefault(s => s.path == path);
var wasValid = scene.IsValid();
var wasLoaded = scene.isLoaded;
if (!wasLoaded)
{
scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
}
var objects = scene.GetRootGameObjects();
var anyChanges = CheckObjects(objects);
if (anyChanges)
{
_ = EditorSceneManager.MarkSceneDirty(scene);
_ = EditorSceneManager.SaveScene(scene);
}
if (!wasLoaded)
{
_ = EditorSceneManager.CloseScene(scene, !wasValid);
}
}
private static IEnumerable<SerializedProperty> GetSerializedProperties(SerializedObject serializedObject)
{
var property = serializedObject.GetIterator();
while (true)
{
yield return property;
if (!property.Next(true))
break;
}
}
private static bool CheckObjects(GameObject[] objects)
{
var anyModified = false;
var componentsByType = objects.
SelectMany(o => o.GetComponentsInChildren<Component>(true)).
WhereNonNull().
GroupBy(c => c.GetType());
foreach (var (type, components) in componentsByType)
{
if (HasAutoSet(type, components))
{
var serializedObject = new SerializedObject(components.ToArray());
foreach (var property in GetSerializedProperties(serializedObject))
{
anyModified = DoAutoSet(property, false) || anyModified;
}
}
}
return anyModified;
}
private static Dictionary<Type, bool> s_componentTypeHasAutoSet = new();
private static bool HasAutoSet(Type type, IEnumerable<Component> components)
{
if (s_componentTypeHasAutoSet.TryGetValue(type, out var hasAutoSet))
return hasAutoSet;
var serializedObject = new SerializedObject(components.ToArray());
var autoSet = GetSerializedProperties(serializedObject).
Select(GetGetComponentFunc).
Any(f => f != null);
s_componentTypeHasAutoSet[type] = autoSet;
return autoSet;
}
private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
internal static GetComponentFunc GetGetComponentFunc(SerializedProperty property)
{
var componentType = property.serializedObject.targetObject.GetType();
var field = GetField(property, componentType);
var attr = GetAutoSetAttribute(field);
if (attr != null)
{
var includeInactive = attr.NamedArguments.
FirstOrDefault(arg => arg.MemberName == "IncludeInactive").
TypedValue.Value is true;
var typeArg = attr.ConstructorArguments.
FirstOrDefault(arg => arg.ArgumentType == typeof(Type)).
Value;
var type = typeArg is Type t ? t : field.FieldType;
if (type.IsArray)
{
var elementType = type.GetElementType();
if (attr.AttributeType == typeof(AutoSetAttribute))
return (target) => target.GetComponents(elementType);
if (attr.AttributeType == typeof(AutoSetFromChildrenAttribute))
return (target) => target.GetComponentsInChildren(elementType, includeInactive);
if (attr.AttributeType == typeof(AutoSetFromParentAttribute))
return (target) => target.GetComponentsInParent(elementType, includeInactive);
}
else
{
if (attr.AttributeType == typeof(AutoSetAttribute))
return (target) => target.GetComponent(type);
if (attr.AttributeType == typeof(AutoSetFromChildrenAttribute))
return (target) => target.GetComponentInChildren(type, includeInactive);
if (attr.AttributeType == typeof(AutoSetFromParentAttribute))
return (target) => target.GetComponentInParent(type, includeInactive);
}
}
return null;
}
private static FieldInfo GetField(SerializedProperty property, Type type)
{
while (type != null)
{
var field = type.GetField(property.name, BINDING_FLAGS);
if (field != null)
return field;
type = type.BaseType;
}
return null;
}
private static CustomAttributeData GetAutoSetAttribute(FieldInfo field) =>
field?.CustomAttributes?.FirstOrDefault(attr =>
typeof(AutoSetAttribute).IsAssignableFrom(attr.AttributeType));
internal static bool DoAutoSet(SerializedProperty property, bool alwaysSet)
{
var getComponent = GetGetComponentFunc(property);
if (getComponent == null)
return false;
var modifiedComponents = property.serializedObject.targetObjects.
OfType<Component>().
Where(target => Apply(property, target, getComponent, alwaysSet)).
ToArray();
if (modifiedComponents.Length != 0)
{
property.serializedObject.SetIsDifferentCacheDirty();
property.serializedObject.Update();
_ = property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
foreach (var component in modifiedComponents)
{
Debug.Log($"AutoSet {property.name} for {component}.", component);
}
}
return modifiedComponents.Length != 0;
}
private static bool Apply(SerializedProperty sourceProperty, Component target, GetComponentFunc getComponent, bool alwaysSet)
{
// create a new SerializedObject for this target, since there may be multiple
using var obj = new SerializedObject(target);
var property = obj.FindProperty(sourceProperty.propertyPath);
if (!property.isArray)
{
if (alwaysSet ||
property.objectReferenceValue is not Component value ||
value == null)
{
property.objectReferenceValue = getComponent(target) as Component;
return obj.ApplyModifiedPropertiesWithoutUndo();
}
}
else
{
if (alwaysSet ||
property.arraySize == 0 ||
property.GetArrayElementAtIndex(0).objectReferenceValue is not Component value ||
value == null)
{
var array = getComponent(target) as Array;
property.arraySize = array.Length;
foreach (var (i, component) in array.Cast<Component>().Enumerate())
property.GetArrayElementAtIndex(i).objectReferenceValue = component;
return obj.ApplyModifiedPropertiesWithoutUndo();
}
}
return false;
}
}
}