-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathEditor.cs
1513 lines (1279 loc) · 58 KB
/
Editor.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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using UnityEditor.AssetImporters;
using UnityEngine;
using UnityEngine.Internal;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
using UnityEngine.UIElements;
using Component = UnityEngine.Component;
using UnityObject = UnityEngine.Object;
namespace UnityEditor
{
interface IPreviewable
{
void Initialize(UnityObject[] targets);
void Cleanup();
UnityObject target { get; }
bool MoveNextTarget();
void ResetTarget();
bool HasPreviewGUI();
GUIContent GetPreviewTitle();
void DrawPreview(Rect previewArea);
VisualElement CreatePreview(VisualElement container);
void OnPreviewGUI(Rect r, GUIStyle background);
void OnInteractivePreviewGUI(Rect r, GUIStyle background);
void OnPreviewSettings();
string GetInfoString();
void ReloadPreviewInstances();
}
public class ObjectPreview : IPreviewable
{
static class Styles
{
public static readonly GUIStyle preBackground = "PreBackground";
public static readonly GUIStyle preBackgroundSolid = "PreBackgroundSolid";
public static readonly GUIStyle previewMiniLabel = "PreMiniLabel";
public static readonly GUIStyle dropShadowLabelStyle = "PreOverlayLabel";
}
const int kPreviewLabelHeight = 12;
const int kPreviewMinSize = 55;
const int kGridTargetCount = 25;
const int kGridSpacing = 10;
const int kPreviewLabelPadding = 5;
protected UnityObject[] m_Targets;
protected int m_ReferenceTargetIndex;
~ObjectPreview()
{
// Watch out for Editor classes implementing OnDisableINTERNAL and not calling cleanup (GenericInspector).
Debug.LogError($"{this} was not disposed properly. Make sure that base.Cleanup is called if overriding " +
$"the Cleanup method. If you are implementing this in an Editor or EditorWindow, don't " +
$"forget to call ObjectPreview.Cleanup in OnDisable.");
}
public virtual void Cleanup()
{
GC.SuppressFinalize(this);
}
public virtual void Initialize(UnityObject[] targets)
{
m_ReferenceTargetIndex = 0;
m_Targets = targets;
}
public virtual bool MoveNextTarget()
{
m_ReferenceTargetIndex++;
return (m_ReferenceTargetIndex < m_Targets.Length - 1);
}
public virtual void ResetTarget()
{
m_ReferenceTargetIndex = 0;
}
public virtual UnityObject target
{
get
{
return m_Targets[m_ReferenceTargetIndex];
}
}
public virtual bool HasPreviewGUI()
{
return false;
}
public virtual VisualElement CreatePreview(VisualElement inspectorPreviewWindow)
{
return null;
}
public virtual GUIContent GetPreviewTitle()
{
GUIContent guiContent = new GUIContent();
guiContent.text = GetPreviewTitleString();
return guiContent;
}
string GetPreviewTitleString()
{
string title = String.Empty;
if (m_Targets.Length == 1)
title = target.name;
else
{
title = m_Targets.Length + " ";
if (NativeClassExtensionUtilities.ExtendsANativeType(target))
title += MonoScript.FromScriptedObject(target).GetClass().Name;
else
title += ObjectNames.NicifyVariableName(ObjectNames.GetClassName(target));
title += "s";
}
return title;
}
public virtual void OnPreviewGUI(Rect r, GUIStyle background)
{
if (Event.current.type == EventType.Repaint)
background.Draw(r, false, false, false, false);
}
public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
OnPreviewGUI(r, background);
}
public virtual void OnPreviewSettings()
{
}
public virtual string GetInfoString()
{
return "";
}
public void DrawPreview(Rect previewArea)
{
DrawPreview(this, previewArea, m_Targets);
}
public virtual void ReloadPreviewInstances()
{
}
internal static void DrawPreview(IPreviewable defaultPreview, Rect previewArea, UnityObject[] targets)
{
string text = string.Empty;
Event evt = Event.current;
// If multiple targets, draw a grid of previews
if (targets.Length > 1)
{
// Draw the previews inside the region of the background that's solid colored
Rect previewPositionInner = new RectOffset(16, 16, 20, 25).Remove(previewArea);
// Number of previews to aim at
int maxRows = Mathf.Max(1, Mathf.FloorToInt((previewPositionInner.height + kGridSpacing) / (kPreviewMinSize + kGridSpacing + kPreviewLabelHeight)));
int maxCols = Mathf.Max(1, Mathf.FloorToInt((previewPositionInner.width + kGridSpacing) / (kPreviewMinSize + kGridSpacing)));
int countWithMinimumSize = maxRows * maxCols;
int neededCount = Mathf.Min(targets.Length, kGridTargetCount);
// Get number of columns and rows
bool fixedSize = true;
int[] division = new int[2] { maxCols, maxRows };
if (neededCount < countWithMinimumSize)
{
division = GetGridDivision(previewPositionInner, neededCount, kPreviewLabelHeight);
fixedSize = false;
}
// The available cells in the grid may be slightly higher than what was aimed at.
// If the number of targets is also higher, we might as well fill in the remaining cells.
int count = Mathf.Min(division[0] * division[1], targets.Length);
// Calculations become simpler if we add one spacing to the width and height,
// so there is the same number of spaces and previews.
previewPositionInner.width += kGridSpacing;
previewPositionInner.height += kGridSpacing;
Vector2 cellSize = new Vector2(
Mathf.FloorToInt(previewPositionInner.width / division[0] - kGridSpacing),
Mathf.FloorToInt(previewPositionInner.height / division[1] - kGridSpacing)
);
float previewSize = Mathf.Min(cellSize.x, cellSize.y - kPreviewLabelHeight);
if (fixedSize)
previewSize = Mathf.Min(previewSize, kPreviewMinSize);
bool selectingOne = (evt.type == EventType.MouseDown && evt.button == 0 && evt.clickCount == 2 &&
previewArea.Contains(evt.mousePosition));
defaultPreview.ResetTarget();
for (int i = 0; i < count; i++)
{
Rect r = new Rect(
previewPositionInner.x + (i % division[0]) * previewPositionInner.width / division[0],
previewPositionInner.y + (i / division[0]) * previewPositionInner.height / division[1],
cellSize.x,
cellSize.y
);
if (selectingOne && r.Contains(Event.current.mousePosition))
{
if (defaultPreview.target is AssetImporter)
// The new selection should be the asset itself, not the importer
Selection.objects = new[] { AssetDatabase.LoadAssetAtPath<UnityObject>(((AssetImporter)defaultPreview.target).assetPath)};
else
Selection.objects = new UnityObject[] {defaultPreview.target};
}
// Make room for label underneath
r.height -= kPreviewLabelHeight;
// Make preview square
Rect rSquare = new Rect(r.x + (r.width - previewSize) * 0.5f, r.y + (r.height - previewSize) * 0.5f, previewSize, previewSize);
// Draw preview inside a group to prevent overdraw
// @TODO: Make style with solid color that doesn't have overdraw
GUI.BeginGroup(rSquare);
Editor.m_AllowMultiObjectAccess = false;
defaultPreview.OnInteractivePreviewGUI(new Rect(0, 0, previewSize, previewSize), Styles.preBackgroundSolid);
Editor.m_AllowMultiObjectAccess = true;
GUI.EndGroup();
// Draw the name of the object
r.y = rSquare.yMax;
r.height = 16;
GUI.Label(r, targets[i].name, Styles.previewMiniLabel);
defaultPreview.MoveNextTarget();
}
defaultPreview.ResetTarget(); // Remember to reset referenceTargetIndex to prevent following calls to 'editor.target' will return a different target which breaks all sorts of places. Fix for case 600235
if (Event.current.type == EventType.Repaint)
text = string.Format("Previewing {0} of {1} Objects", count, targets.Length);
}
// If only a single target, just draw that one
else
{
defaultPreview.OnInteractivePreviewGUI(previewArea, Styles.preBackground);
if (Event.current.type == EventType.Repaint)
{
// TODO: This should probably be calculated during import and stored together with the asset somehow. Or maybe not. Not sure, really...
text = defaultPreview.GetInfoString();
if (text != string.Empty)
{
text = text.Replace("\n", " ");
text = string.Format("{0}\n{1}", defaultPreview.target.name, text);
}
}
}
// Draw the asset info.
if (Event.current.type == EventType.Repaint && text != string.Empty)
{
var textHeight = Styles.dropShadowLabelStyle.CalcHeight(GUIContent.Temp(text), previewArea.width);
EditorGUI.DropShadowLabel(new Rect(previewArea.x, previewArea.yMax - textHeight - kPreviewLabelPadding, previewArea.width, textHeight), text);
}
}
// Get the number or columns and rows for a grid with a certain minimum number of cells
// such that the cells are as close to square as possible.
private static int[] GetGridDivision(Rect rect, int minimumNr, int labelHeight)
{
// The edge size of a square calculated based on area
float approxSize = Mathf.Sqrt(rect.width * rect.height / minimumNr);
int xCount = Mathf.FloorToInt(rect.width / approxSize);
int yCount = Mathf.FloorToInt(rect.height / (approxSize + labelHeight));
// This heuristic is not entirely optimal and could probably be improved
while (xCount * yCount < minimumNr)
{
float ratioIfXInc = AbsRatioDiff((xCount + 1) / rect.width, yCount / (rect.height - yCount * labelHeight));
float ratioIfYInc = AbsRatioDiff(xCount / rect.width, (yCount + 1) / (rect.height - (yCount + 1) * labelHeight));
if (ratioIfXInc < ratioIfYInc)
{
xCount++;
if (xCount * yCount > minimumNr)
yCount = Mathf.CeilToInt((float)minimumNr / xCount);
}
else
{
yCount++;
if (xCount * yCount > minimumNr)
xCount = Mathf.CeilToInt((float)minimumNr / yCount);
}
}
return new int[] { xCount, yCount };
}
private static float AbsRatioDiff(float x, float y)
{
return Mathf.Max(x / y, y / x);
}
}
internal interface IToolModeOwner
{
bool areToolModesAvailable { get; }
int GetInstanceID();
Bounds GetWorldBoundsOfTargets();
bool ModeSurvivesSelectionChange(int toolMode);
}
[Obsolete(@"CustomEditorForRenderPipelineAttribute is deprecated. Use CustomEditor with SupportedOnCurrentPipeline instead. #from(2023.1)", false)]
[AttributeUsage(AttributeTargets.Class)]
public class CustomEditorForRenderPipelineAttribute : CustomEditor
{
internal Type renderPipelineType;
public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline) : base(inspectedType)
{
if (renderPipeline != null && !typeof(RenderPipelineAsset).IsAssignableFrom(renderPipeline))
Debug.LogError($"The CustomEditorForRenderPipeline Attribute targets an invalid RenderPipelineAsset. {renderPipeline} cannot be assigned from RenderPipelineAsset.");
renderPipelineType = renderPipeline;
}
public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline, bool editorForChildClasses) : base(inspectedType, editorForChildClasses)
{
if (renderPipeline != null && !typeof(RenderPipelineAsset).IsAssignableFrom(renderPipeline))
Debug.LogError($"The CustomEditorForRenderPipeline Attribute targets an invalid RenderPipelineAsset. {renderPipeline} cannot be assigned from RenderPipelineAsset.");
renderPipelineType = renderPipeline;
}
}
public sealed partial class CanEditMultipleObjects : System.Attribute {}
[AttributeUsage(AttributeTargets.Field)]
internal sealed class CachePropertyAttribute : System.Attribute
{
public string propertyPath { get; }
public CachePropertyAttribute()
{
propertyPath = null;
}
public CachePropertyAttribute(string propertyPath)
{
this.propertyPath = propertyPath;
}
}
internal interface ICoupledEditor
{
SerializedObject coupledComponent { get; }
}
// Base class to derive custom Editors from. Use this to create your own custom inspectors and editors for your objects.
[ExcludeFromObjectFactory]
public partial class Editor : ScriptableObject, IPreviewable, IToolModeOwner
{
//If you modify the members of the Editor class, please keep in mind
//that you need to keep the c++ struct MonoInspectorData in sync.
//Last time this struct could be found at: Editor\src\Utility\CreateEditor.cpp
// The object currently inspected by this editor.
UnityObject[] m_Targets;
// The context object with which this Editor was created
internal UnityObject m_Context;
// Note that m_Dirty is not only set through 'isInspectorDirty' but also from C++ in 'SetCustomEditorIsDirty (MonoBehaviour* inspector, bool dirty)'
int m_IsDirty;
int m_ReferenceTargetIndex = 0;
PropertyHandlerCache m_PropertyHandlerCache = new PropertyHandlerCache();
IPreviewable m_DummyPreview;
AudioFilterGUI m_AudioFilterGUI;
internal SerializedObject m_SerializedObject = null;
internal SerializedProperty m_EnabledProperty = null;
private InspectorMode m_InspectorMode = InspectorMode.Normal;
internal InspectorMode inspectorMode
{
get
{
return propertyViewer?.inspectorMode ?? m_InspectorMode;
}
set
{
if (m_InspectorMode != value)
{
m_InspectorMode = value;
m_SerializedObject = null;
m_EnabledProperty = null;
}
}
}
internal DataMode dataMode =>
propertyViewer is EditorWindow editorWindow
? editorWindow.dataModeController.dataMode
: DataMode.Disabled;
internal static float kLineHeight = EditorGUI.kSingleLineHeight;
internal bool hideInspector = false;
const float kImageSectionWidth = 44;
internal const float k_WideModeMinWidth = 330f;
internal const float k_HeaderHeight = 21f;
internal delegate void OnEditorGUIDelegate(Editor editor, Rect drawRect);
internal static OnEditorGUIDelegate OnPostIconGUI = null;
internal static bool m_AllowMultiObjectAccess = true;
bool m_HasUnsavedChanges = false;
[UsedByNativeCode]
private bool GetHasUnsavedChanges()
{
return hasUnsavedChanges;
}
public bool hasUnsavedChanges
{
get
{
return m_HasUnsavedChanges;
}
protected set
{
if (m_HasUnsavedChanges != value)
{
m_HasUnsavedChanges = value;
if (propertyViewer != null)
{
propertyViewer.UnsavedChangesStateChanged(this, value);
}
}
}
}
public string saveChangesMessage { get; protected set; }
public virtual void SaveChanges()
{
hasUnsavedChanges = false;
}
public virtual void DiscardChanges()
{
hasUnsavedChanges = false;
}
// used internally to know if this the first editor in the inspector window
internal bool firstInspectedEditor { get; set; }
IPropertyView m_PropertyViewer;
internal IPropertyView propertyViewer
{
get
{
return m_PropertyViewer;
}
set
{
if (m_PropertyViewer != value)
{
m_PropertyViewer = value;
// We are being assigned a new property view with different inspector mode to what our serialized object was built with.
if (null != m_PropertyViewer && m_PropertyViewer.inspectorMode != m_InspectorMode)
{
// Keep the local inspector mode in sync.
m_InspectorMode = m_PropertyViewer.inspectorMode;
// Trash the local serialized object and property cache to force a rebuild.
m_SerializedObject = null;
m_EnabledProperty = null;
}
}
}
}
internal virtual bool HasLargeHeader()
{
return AssetDatabase.IsMainAsset(target) || AssetDatabase.IsSubAsset(target);
}
internal bool canEditMultipleObjects
{
get
{
return Attribute.IsDefined(GetType(), typeof(CanEditMultipleObjects), false);
}
}
internal virtual IPreviewable preview
{
get
{
if (m_DummyPreview == null)
{
m_DummyPreview = new ObjectPreview();
m_DummyPreview.Initialize(targets);
}
return m_DummyPreview;
}
}
internal PropertyHandlerCache propertyHandlerCache
{
get { return m_PropertyHandlerCache; }
}
static class BaseStyles
{
public static readonly GUIContent open = EditorGUIUtility.TrTextContent("Open");
public static readonly GUIStyle inspectorBig = new GUIStyle(EditorStyles.inspectorBig);
public static readonly GUIStyle centerStyle = new GUIStyle();
public static readonly GUIStyle postLargeHeaderBackground = "IN BigTitle Post";
static BaseStyles()
{
centerStyle.alignment = TextAnchor.MiddleCenter;
}
}
bool IToolModeOwner.areToolModesAvailable
{
get
{
// tool modes not available when the target is a prefab parent
return !EditorUtility.IsPersistent(target);
}
}
// The object being inspected.
public UnityObject target { get { return m_Targets[referenceTargetIndex]; } set { throw new InvalidOperationException("You can't set the target on an editor."); } }
// An array of all the object being inspected.
public UnityObject[] targets
{
get
{
if (!m_AllowMultiObjectAccess)
Debug.LogError("The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead.");
return m_Targets;
}
}
internal virtual int referenceTargetIndex
{
get { return Mathf.Clamp(m_ReferenceTargetIndex, 0, m_Targets.Length - 1); }
// Modulus that works for negative numbers as well
set { m_ReferenceTargetIndex = (Math.Abs(value * m_Targets.Length) + value) % m_Targets.Length; }
}
internal virtual string targetTitle
{
get
{
if (m_Targets.Length == 1 || !m_AllowMultiObjectAccess)
return ObjectNames.GetInspectorTitle(target);
else
return m_Targets.Length + " " + ObjectNames.NicifyVariableName(ObjectNames.GetTypeName(target)) + "s";
}
}
// A [[SerializedObject]] representing the object or objects being inspected.
public SerializedObject serializedObject
{
get
{
if (!m_AllowMultiObjectAccess)
Debug.LogError("The serializedObject should not be used inside OnSceneGUI or OnPreviewGUI. Use the target property directly instead.");
return GetSerializedObjectInternal();
}
}
internal SerializedProperty enabledProperty
{
get
{
GetSerializedObjectInternal();
return m_EnabledProperty;
}
}
internal bool isInspectorDirty
{
get { return m_IsDirty != 0; }
set { m_IsDirty = value ? 1 : 0; }
}
public static Editor CreateEditorWithContext(UnityObject[] targetObjects, UnityObject context, [UnityEngine.Internal.DefaultValue("null")] Type editorType)
{
if (editorType != null && !editorType.IsSubclassOf(typeof(Editor)))
throw new ArgumentException($"Editor type '{editorType}' does not derive from UnityEditor.Editor", "editorType");
return CreateEditorWithContextInternal(targetObjects, context, editorType);
}
[ExcludeFromDocs]
public static Editor CreateEditorWithContext(UnityObject[] targetObjects, UnityObject context)
{
Type editorType = null;
return CreateEditorWithContext(targetObjects, context, editorType);
}
public static void CreateCachedEditorWithContext(UnityObject targetObject, UnityObject context, Type editorType, ref Editor previousEditor)
{
CreateCachedEditorWithContext(new[] {targetObject}, context, editorType, ref previousEditor);
}
public static void CreateCachedEditorWithContext(UnityObject[] targetObjects, UnityObject context, Type editorType, ref Editor previousEditor)
{
if (previousEditor != null && ArrayUtility.ArrayEquals(previousEditor.m_Targets, targetObjects) && previousEditor.m_Context == context)
return;
if (previousEditor != null)
DestroyImmediate(previousEditor);
previousEditor = CreateEditorWithContext(targetObjects, context, editorType);
}
public static void CreateCachedEditor(UnityObject targetObject, Type editorType, ref Editor previousEditor)
{
CreateCachedEditorWithContext(new[] {targetObject}, null, editorType, ref previousEditor);
}
public static void CreateCachedEditor(UnityObject[] targetObjects, Type editorType, ref Editor previousEditor)
{
CreateCachedEditorWithContext(targetObjects, null, editorType, ref previousEditor);
}
[ExcludeFromDocs]
public static Editor CreateEditor(UnityObject targetObject)
{
Type editorType = null;
return CreateEditor(targetObject, editorType);
}
public static Editor CreateEditor(UnityObject targetObject, [UnityEngine.Internal.DefaultValue("null")] Type editorType)
{
return CreateEditorWithContext(new[] {targetObject}, null, editorType);
}
[ExcludeFromDocs]
public static Editor CreateEditor(UnityObject[] targetObjects)
{
Type editorType = null;
return CreateEditor(targetObjects, editorType);
}
public static Editor CreateEditor(UnityObject[] targetObjects, [UnityEngine.Internal.DefaultValue("null")] Type editorType)
{
return CreateEditorWithContext(targetObjects, null, editorType);
}
internal void CleanupPropertyEditor()
{
if (m_SerializedObject != null)
{
m_SerializedObject.Dispose();
m_SerializedObject = null;
}
}
private void OnDisableINTERNAL()
{
CleanupPropertyEditor();
if (!(preview is Editor))
preview.Cleanup();
}
internal virtual SerializedObject GetSerializedObjectInternal()
{
if (m_SerializedObject == null)
{
CreateSerializedObject();
}
return m_SerializedObject;
}
internal class SerializedObjectNotCreatableException : Exception
{
public SerializedObjectNotCreatableException(string msg) : base(msg) {}
}
private void CreateSerializedObject()
{
try
{
m_SerializedObject = new SerializedObject(targets, m_Context);
m_SerializedObject.inspectorMode = inspectorMode;
if (m_SerializedObject.inspectorDataMode != dataMode)
m_SerializedObject.inspectorDataMode = dataMode;
AssignCachedProperties(this, m_SerializedObject.GetIterator());
m_EnabledProperty = m_SerializedObject.FindProperty("m_Enabled");
}
catch (ArgumentException e)
{
m_SerializedObject = null;
m_EnabledProperty = null;
throw new SerializedObjectNotCreatableException(e.Message);
}
}
internal static void AssignCachedProperties<T>(T self, SerializedProperty root) where T : class
{
var fields = ScriptAttributeUtility.GetAutoLoadProperties(typeof(T));
if (fields.Count == 0)
return;
var properties = new Dictionary<string, FieldInfo>(fields.Count);
var allParents = new HashSet<string>();
foreach (var fieldInfo in fields)
{
var attribute = (CachePropertyAttribute)fieldInfo.GetCustomAttributes(typeof(CachePropertyAttribute), false).First();
var propertyName = string.IsNullOrEmpty(attribute.propertyPath) ? fieldInfo.Name : attribute.propertyPath;
properties.Add(propertyName, fieldInfo);
int dot = propertyName.LastIndexOf('.');
while (dot != -1)
{
propertyName = propertyName.Substring(0, dot);
if (!allParents.Add(propertyName))
break;
dot = propertyName.LastIndexOf('.');
}
}
var parentPath = root.propertyPath;
var parentPathLength = parentPath.Length > 0 ? parentPath.Length + 1 : 0;
var exitCount = properties.Count;
var iterator = root.Copy();
bool enterChildren = true;
while (iterator.Next(enterChildren) && exitCount > 0)
{
FieldInfo fieldInfo;
var propertyPath = iterator.propertyPath.Substring(parentPathLength);
if (properties.TryGetValue(propertyPath, out fieldInfo))
{
fieldInfo.SetValue(self, iterator.Copy());
properties.Remove(propertyPath);
exitCount--;
}
enterChildren = allParents.Contains(propertyPath);
}
iterator.Dispose();
if (exitCount > 0)
{
Debug.LogWarning("The following properties registered with CacheProperty where not found during the inspector creation: " + string.Join(", ", properties.Keys.ToArray()));
}
}
internal void InternalSetTargets(UnityObject[] t) { m_Targets = t; }
internal void InternalSetHidden(bool hidden) { hideInspector = hidden; }
internal void InternalSetContextObject(UnityObject context) { m_Context = context; }
Bounds IToolModeOwner.GetWorldBoundsOfTargets()
{
var result = new Bounds();
bool initialized = false;
foreach (var t in targets)
{
if (t == null)
continue;
Bounds targetBounds = GetWorldBoundsOfTarget(t);
if (!initialized)
result = targetBounds;
result.Encapsulate(targetBounds);
initialized = true;
}
return result;
}
internal virtual Bounds GetWorldBoundsOfTarget(UnityObject targetObject)
{
return targetObject is Component ? ((Component)targetObject).gameObject.CalculateBounds() : new Bounds();
}
bool IToolModeOwner.ModeSurvivesSelectionChange(int toolMode)
{
return false;
}
// Reload SerializedObject because flags etc might have changed.
internal virtual void OnForceReloadInspector()
{
if (m_SerializedObject != null)
{
m_SerializedObject.SetIsDifferentCacheDirty();
// Need to make sure internal target list PPtr have been updated from a native memory
// When assets are reloaded they are destroyed and recreated and the managed list does not get updated
// The m_SerializedObject is a native object thus its targetObjects is a native memory PPtr list which have the new PPtr ids.
InternalSetTargets(m_SerializedObject.targetObjects);
}
}
internal virtual bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out float height)
{
height = -1;
return false;
}
internal virtual bool OnOptimizedInspectorGUI(Rect contentRect)
{
Debug.LogError("Not supported");
return false;
}
protected internal static void DrawPropertiesExcluding(SerializedObject obj, params string[] propertyToExclude)
{
// Loop through properties and create one field (including children) for each top level property.
SerializedProperty property = obj.GetIterator();
bool expanded = true;
while (property.NextVisible(expanded))
{
expanded = false;
if (propertyToExclude.Contains(property.name))
continue;
EditorGUILayout.PropertyField(property, true);
}
}
// Draw the built-in inspector.
public bool DrawDefaultInspector()
{
return DoDrawDefaultInspector();
}
internal static bool DoDrawDefaultInspector(SerializedObject obj)
{
EditorGUI.BeginChangeCheck();
obj.UpdateIfRequiredOrScript();
// Loop through properties and create one field (including children) for each top level property.
SerializedProperty property = obj.GetIterator();
bool expanded = true;
while (property.NextVisible(expanded))
{
using (new EditorGUI.DisabledScope("m_Script" == property.propertyPath))
{
EditorGUILayout.PropertyField(property, true);
}
expanded = false;
}
obj.ApplyModifiedProperties();
return EditorGUI.EndChangeCheck();
}
internal bool DoDrawDefaultInspector()
{
bool res;
using (new LocalizationGroup(target))
{
res = DoDrawDefaultInspector(serializedObject);
var behaviour = target as MonoBehaviour;
if (behaviour == null || !AudioUtil.HasAudioCallback(behaviour) || AudioUtil.GetCustomFilterChannelCount(behaviour) <= 0)
return res;
// If we have an OnAudioFilterRead callback, draw vu meter
if (m_AudioFilterGUI == null)
m_AudioFilterGUI = new AudioFilterGUI();
m_AudioFilterGUI.DrawAudioFilterGUI(behaviour);
}
return res;
}
// Repaint any inspectors that shows this editor.
public void Repaint()
{
if (propertyViewer != null)
propertyViewer.Repaint();
else
InspectorWindow.RepaintAllInspectors();
}
// Implement this function to make a custom IMGUI inspector.
public virtual void OnInspectorGUI()
{
DrawDefaultInspector();
}
// Implement this function to make a custom UIElements inspector.
public virtual VisualElement CreateInspectorGUI()
{
return null;
}
// Implement this function if you want your editor constantly repaint (every 33ms)
public virtual bool RequiresConstantRepaint()
{
return false;
}
public static event Action<Editor> finishedDefaultHeaderGUI = null;
// This is the method that should be called from externally e.g. myEditor.DrawHeader ();
// Do not make this method virtual - override OnHeaderGUI instead.
public void DrawHeader()
{
// If we call DrawHeader from inside an an editor's OnInspectorGUI call, we have to do special handling.
// (See DrawHeaderFromInsideHierarchy for details.)
// We know we're inside the OnInspectorGUI block (or a similar vertical block) if hierarchyMode is set to true.
var hierarchyMode = EditorGUIUtility.hierarchyMode;
if (hierarchyMode)
DrawHeaderFromInsideHierarchy();
else
OnHeaderGUI();
if (finishedDefaultHeaderGUI != null)
{
// see DrawHeaderFromInsideHierarchy()
if (hierarchyMode)
{
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical(GUILayoutUtility.topLevel.style);
}
// reset label and field widths to defaults
EditorGUIUtility.labelWidth = 0f;
EditorGUIUtility.fieldWidth = 0f;
GUILayout.Space(
-1f // move up to cover up bottom pixel of header box
- BaseStyles.inspectorBig.margin.bottom
- BaseStyles.inspectorBig.padding.bottom
- BaseStyles.inspectorBig.overflow.bottom // move up to bottom of content area in header
);
// align with controls in the Inspector
// see InspectorWindow.DrawEditor() before calls to OnOptimizedInspectorGUI()/OnInspectorGUI()
EditorGUIUtility.hierarchyMode = true;
EditorGUIUtility.wideMode = EditorGUIUtility.contextWidth > k_WideModeMinWidth;
EditorGUILayout.BeginVertical(BaseStyles.postLargeHeaderBackground, GUILayout.ExpandWidth(true));
finishedDefaultHeaderGUI(this);
EditorGUILayout.EndVertical();
if (hierarchyMode)
{
EditorGUILayout.EndVertical();
// see InspectorWindow.DoOnInspectorGUI()
EditorGUILayout.BeginVertical(UseDefaultMargins() ? EditorStyles.inspectorDefaultMargins : GUIStyle.none);
}
}
// Restore previous hierarchy mode
EditorGUIUtility.hierarchyMode = hierarchyMode;
}
// This is the method to override to create custom header GUI.
// Do not make this method internal or public - call DrawHeader instead.
protected virtual void OnHeaderGUI()
{
DrawHeaderGUI(this, targetTitle);
}
internal virtual void OnHeaderControlsGUI()
{
// Ensure we take up the same amount of height as regular controls
GUILayoutUtility.GetRect(10, 10, 16, 16, EditorStyles.layerMaskField);
GUILayout.FlexibleSpace();
bool showOpenButton = true;
var importerEditor = this as AssetImporterEditor;
// only show open button for the main object of an asset and for AssetImportInProgressProxy (asset not yet imported)
if (importerEditor == null && !(targets[0] is AssetImportInProgressProxy))
{
var assetPath = AssetDatabase.GetAssetPath(targets[0]);
// Don't show open button if the target is not an asset
if (!AssetDatabase.IsMainAsset(targets[0]))
showOpenButton = false;
// Don't show open button if the target has an importer
// (but ignore AssetImporters since they're not shown)
AssetImporter importer = AssetImporter.GetAtPath(assetPath);
if (importer && importer.GetType() != typeof(AssetImporter))
showOpenButton = false;