-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathComponentConnector.cs
More file actions
487 lines (392 loc) · 19.1 KB
/
Copy pathComponentConnector.cs
File metadata and controls
487 lines (392 loc) · 19.1 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Component Connector V2
// https://github.com/synchrok/ComponentConnector
// MIT License
using System;
#if UNITY_EDITOR
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.Events;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
#endif
public interface IComponentConnector { }
[AttributeUsage(AttributeTargets.Field)]
public class ComponentConnectAttribute : Attribute {
public string name { get; }
public bool inChildren { get; }
public ComponentConnectAttribute(string name, bool inChildren = false) {
this.name = name;
this.inChildren = inChildren;
}
public ComponentConnectAttribute() {
name = null;
inChildren = true;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class OnClickAttribute : Attribute {
public string name { get; }
public bool inChildren { get; }
public OnClickAttribute(string name, bool inChildren = false) {
this.name = name;
this.inChildren = inChildren;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class GetComponentAttribute : Attribute { }
/// <summary>
/// Legacy stub. 기존 씬/프리팹 호환용 — 새 시스템은 ComponentConnectorProcessor가 처리.
/// 씬/프리팹에서 이 컴포넌트를 제거한 뒤 이 클래스도 삭제 가능.
/// </summary>
public class ComponentConnector : UnityEngine.MonoBehaviour { }
#if UNITY_EDITOR
[InitializeOnLoad]
public static class ComponentConnectorProcessor {
// ──────────────────────────────────────────────────────────────
// Reflection Cache
// ──────────────────────────────────────────────────────────────
private struct ConnectFieldEntry {
public FieldInfo Field;
public string Name;
public bool InChildren;
}
private struct OnClickEntry {
public MethodInfo Method;
public string ButtonName;
public bool InChildren;
}
private struct GetComponentEntry {
public FieldInfo Field;
}
private class CachedType {
public ConnectFieldEntry[] ConnectFields;
public OnClickEntry[] OnClickMethods;
public GetComponentEntry[] GetComponentFields;
public bool HasAny;
}
private static readonly Dictionary<Type, CachedType> _cache = new();
private static bool _processScheduled;
// ──────────────────────────────────────────────────────────────
// Initialization
// ──────────────────────────────────────────────────────────────
static ComponentConnectorProcessor() {
EditorApplication.hierarchyChanged += OnHierarchyChanged;
PrefabStage.prefabStageOpened += OnPrefabStageOpened;
PrefabStage.prefabSaving += OnPrefabSaving;
}
private static void OnHierarchyChanged() {
if (Application.isPlaying) return;
if (EditorApplication.isCompiling || EditorApplication.isUpdating) return;
if (_processScheduled) return;
_processScheduled = true;
EditorApplication.delayCall += () => {
_processScheduled = false;
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
ProcessGameObject(prefabStage.prefabContentsRoot);
else
ProcessActiveScene();
};
}
private static void OnPrefabStageOpened(PrefabStage stage) {
ProcessGameObject(stage.prefabContentsRoot);
}
private static void OnPrefabSaving(GameObject root) {
ProcessGameObject(root);
}
// ──────────────────────────────────────────────────────────────
// Public API
// ──────────────────────────────────────────────────────────────
[MenuItem("CONTEXT/Component/Component Connect", false, int.MaxValue)]
public static void ContextRun() {
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
ProcessGameObject(prefabStage.prefabContentsRoot);
else
ProcessActiveScene();
}
public static void ProcessActiveScene() {
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var root in roots)
ProcessGameObject(root);
}
public static void ProcessGameObject(GameObject root) {
var components = root.GetComponentsInChildren<Component>(true);
foreach (var comp in components) {
if (comp == null) continue;
var cached = GetOrBuild(comp.GetType());
if (!cached.HasAny) continue;
ProcessComponent(comp, cached);
}
}
// ──────────────────────────────────────────────────────────────
// Cache
// ──────────────────────────────────────────────────────────────
private static CachedType GetOrBuild(Type type) {
if (_cache.TryGetValue(type, out var cached))
return cached;
cached = Build(type);
_cache[type] = cached;
return cached;
}
private static CachedType Build(Type type) {
var ct = new CachedType();
var isCC = typeof(IComponentConnector).IsAssignableFrom(type);
var connects = new List<ConnectFieldEntry>();
var getComps = new List<GetComponentEntry>();
var clicks = new List<OnClickEntry>();
var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var fi in fields) {
foreach (var attr in fi.GetCustomAttributes(true)) {
if (attr is ComponentConnectAttribute cca)
connects.Add(new ConnectFieldEntry {
Field = fi,
Name = cca.name ?? fi.Name,
InChildren = cca.inChildren
});
else if (attr is GetComponentAttribute)
getComps.Add(new GetComponentEntry { Field = fi });
}
}
if (isCC) {
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var mi in methods) {
foreach (var attr in mi.GetCustomAttributes(typeof(OnClickAttribute), true)) {
if (attr is OnClickAttribute oca)
clicks.Add(new OnClickEntry {
Method = mi,
ButtonName = oca.name,
InChildren = oca.inChildren
});
}
}
}
ct.ConnectFields = connects.ToArray();
ct.GetComponentFields = getComps.ToArray();
ct.OnClickMethods = clicks.ToArray();
ct.HasAny = connects.Count > 0 || getComps.Count > 0 || clicks.Count > 0;
return ct;
}
// ──────────────────────────────────────────────────────────────
// Processing
// ──────────────────────────────────────────────────────────────
private static void ProcessComponent(Component mb, CachedType cached) {
bool changed = false;
bool undoRecorded = false;
foreach (var entry in cached.ConnectFields) {
if (ShouldSkip(entry.Field, mb)) continue;
if (TryConnect(mb, entry, ref undoRecorded))
changed = true;
}
foreach (var entry in cached.GetComponentFields) {
if (ShouldSkip(entry.Field, mb)) continue;
if (TryGetComp(mb, entry, ref undoRecorded))
changed = true;
}
foreach (var entry in cached.OnClickMethods) {
if (TryOnClick(mb, entry))
changed = true;
}
if (changed)
EditorUtility.SetDirty(mb);
}
// ──────────────────────────────────────────────────────────────
// Skip Logic
// ──────────────────────────────────────────────────────────────
private static bool ShouldSkip(FieldInfo fi, Component mb) {
var value = fi.GetValue(mb);
if (value == null) return false;
if (value is UnityEngine.Object obj)
return obj != null; // alive → skip; destroyed → reconnect
if (fi.FieldType.IsArray)
return value is Array arr && arr.Length > 0;
return true;
}
// ──────────────────────────────────────────────────────────────
// [ComponentConnect]
// ──────────────────────────────────────────────────────────────
private static bool TryConnect(Component mb, ConnectFieldEntry entry, ref bool undoRecorded) {
var name = entry.Name;
var inChildren = entry.InChildren;
if (name.EndsWith("~"))
return TryConnectArray(mb, entry.Field, name.TrimEnd('~'), inChildren, ref undoRecorded);
GameObject go;
if (name.Contains("..."))
go = ResolveEllipsis(mb, name, inChildren);
else
go = ResolveStandard(mb, name, inChildren);
if (go == null) return false;
object newValue;
if (entry.Field.FieldType == typeof(GameObject))
newValue = go;
else {
var comp = go.GetComponent(entry.Field.FieldType);
if (comp == null) return false;
newValue = comp;
}
RecordUndo(mb, ref undoRecorded);
entry.Field.SetValue(mb, newValue);
return true;
}
private static bool TryConnectArray(Component mb, FieldInfo fi, string keyword,
bool inChildren, ref bool undoRecorded) {
var searched = CCSearchAllStartsWith(mb.gameObject, keyword);
if (searched == null && !inChildren)
searched = CCSearchAllStartsWith(mb.transform.root.gameObject, keyword);
if (searched == null)
searched = CCSearchAllStartsWithSceneRoots(keyword);
if (searched == null) return false;
RecordUndo(mb, ref undoRecorded);
if (fi.FieldType == typeof(GameObject[])) {
fi.SetValue(mb, searched);
} else {
var elemType = fi.FieldType.GetElementType();
var arr = Array.CreateInstance(elemType, searched.Length);
for (var i = 0; i < searched.Length; i++)
arr.SetValue(searched[i].GetComponent(elemType), i);
fi.SetValue(mb, arr);
}
return true;
}
private static GameObject ResolveStandard(Component mb, string name, bool inChildren) {
var go = CCSearch(mb.gameObject, name);
if (go == null && !inChildren)
go = CCSearch(mb.transform.root.gameObject, name);
if (go == null)
go = CCSearchSceneRoots(name, mb.transform.root.gameObject);
return go;
}
private static GameObject ResolveEllipsis(Component mb, string ccName, bool inChildren) {
var d = ccName.Split(new[] { "..." }, StringSplitOptions.RemoveEmptyEntries);
if (d.Length == 1) {
var go = CCSearch(mb.gameObject, d[0]);
if (go == null && !inChildren)
go = CCSearch(mb.transform.root.gameObject, d[0]);
if (go == null)
go = CCSearchSceneRoots(d[0], mb.transform.root.gameObject);
return go;
}
var result = CCSearchWithParentName(mb.gameObject, d[1], d[0]);
if (result == null && !inChildren)
result = CCSearchWithParentName(mb.transform.root.gameObject, d[1], d[0]);
if (result == null) {
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var root in roots) {
if (root == mb.transform.root.gameObject) continue;
result = CCSearchWithParentName(root, d[1], d[0]);
if (result != null) break;
}
}
return result;
}
// ──────────────────────────────────────────────────────────────
// [GetComponent]
// ──────────────────────────────────────────────────────────────
private static bool TryGetComp(Component mb, GetComponentEntry entry, ref bool undoRecorded) {
if (mb.gameObject == null) return false;
object newValue;
if (entry.Field.FieldType == typeof(GameObject))
newValue = mb.gameObject;
else {
var comp = mb.gameObject.GetComponent(entry.Field.FieldType);
if (comp == null) return false;
newValue = comp;
}
RecordUndo(mb, ref undoRecorded);
entry.Field.SetValue(mb, newValue);
return true;
}
// ──────────────────────────────────────────────────────────────
// [OnClick]
// ──────────────────────────────────────────────────────────────
private static bool TryOnClick(Component mb, OnClickEntry entry) {
var go = CCSearch(mb.gameObject, entry.ButtonName);
if (go == null && !entry.InChildren)
go = CCSearch(mb.transform.root.gameObject, entry.ButtonName);
if (go == null) return false;
var btn = go.GetComponent<Button>();
if (btn == null) return false;
var pcnt = btn.onClick.GetPersistentEventCount();
if (pcnt == 1 &&
btn.onClick.GetPersistentTarget(0) == (UnityEngine.Object)mb &&
btn.onClick.GetPersistentMethodName(0) == entry.Method.Name)
return false;
Undo.RecordObject(btn, "ComponentConnector");
for (var i = pcnt - 1; i >= 0; i--)
UnityEventTools.RemovePersistentListener(btn.onClick, 0);
var action = Delegate.CreateDelegate(typeof(UnityAction), mb, entry.Method.Name) as UnityAction;
UnityEventTools.AddPersistentListener(btn.onClick, action);
EditorUtility.SetDirty(btn);
return true;
}
// ──────────────────────────────────────────────────────────────
// Undo
// ──────────────────────────────────────────────────────────────
private static void RecordUndo(Component mb, ref bool undoRecorded) {
if (undoRecorded) return;
Undo.RecordObject(mb, "ComponentConnector");
undoRecorded = true;
}
// ──────────────────────────────────────────────────────────────
// CC Search (Private)
// ──────────────────────────────────────────────────────────────
private static GameObject CCSearch(GameObject target, string name) {
if (string.Equals(target.name, name, StringComparison.OrdinalIgnoreCase))
return target;
for (var i = 0; i < target.transform.childCount; i++) {
var result = CCSearch(target.transform.GetChild(i).gameObject, name);
if (result != null) return result;
}
return null;
}
private static GameObject CCSearchWithParentName(GameObject target, string name, string parentName) {
if (string.Equals(target.name, parentName, StringComparison.OrdinalIgnoreCase)) {
for (var i = 0; i < target.transform.childCount; i++) {
var child = target.transform.GetChild(i);
if (child.name.Equals(name))
return child.gameObject;
}
}
for (var i = 0; i < target.transform.childCount; i++) {
var result = CCSearchWithParentName(target.transform.GetChild(i).gameObject, name, parentName);
if (result != null) return result;
}
return null;
}
private static readonly List<GameObject> _ccSearchList = new();
private static GameObject[] CCSearchAllStartsWith(GameObject target, string keyword) {
_ccSearchList.Clear();
CCSearchAllStartsWithImpl(target, keyword);
return _ccSearchList.Count > 0 ? _ccSearchList.ToArray() : null;
}
private static void CCSearchAllStartsWithImpl(GameObject target, string keyword) {
if (target.name.StartsWith(keyword)) {
_ccSearchList.Add(target);
return;
}
for (var i = 0; i < target.transform.childCount; i++)
CCSearchAllStartsWithImpl(target.transform.GetChild(i).gameObject, keyword);
}
private static GameObject CCSearchSceneRoots(string name, GameObject exclude) {
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var root in roots) {
if (root == exclude) continue;
var go = CCSearch(root, name);
if (go != null) return go;
}
return null;
}
private static GameObject[] CCSearchAllStartsWithSceneRoots(string keyword) {
var roots = SceneManager.GetActiveScene().GetRootGameObjects();
foreach (var root in roots) {
var result = CCSearchAllStartsWith(root, keyword);
if (result != null) return result;
}
return null;
}
}
#endif