-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathObjectDrawer.cs
835 lines (693 loc) · 30.2 KB
/
ObjectDrawer.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
#if UNITY_EDITOR
#if UNITY_2021_2_OR_NEWER
using UnityEditor.SceneManagement;
#else
using UnityEditor.Experimental.SceneManagement;
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.Assertions;
using static UnityEditor.AssetDatabase;
using Object = UnityEngine.Object;
namespace cratesmith.assetui
{
[CustomPropertyDrawer(typeof(Object), true)]
public class ObjectDrawer : PropertyDrawer
{
static Texture2D s_ExpandButton;
static Texture2D s_NewButton;
static HashSet<ScriptableObject> s_CyclicCheck = new HashSet<ScriptableObject>();
static Texture2D ExpandButton => s_ExpandButton
? s_ExpandButton
: s_ExpandButton = LoadAssetAtPath<Texture2D>(
GUIDToAssetPath(
FindAssets("objectdrawer_expand t:texture").FirstOrDefault()));
static Texture2D NewButton => s_NewButton
? s_NewButton
: s_NewButton = LoadAssetAtPath<Texture2D>(
GUIDToAssetPath(
FindAssets("objectdrawer_new t:texture").FirstOrDefault()));
static Dictionary<Type, (Type type, string displayName, string fileName, string fileExtension)[]> s_cachedTypes = new Dictionary<Type, (Type type, string displayName, string fileName, string fileExtension)[]>();
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float baseHeight = EditorGUIUtility.singleLineHeight;
ScriptableObject data = property!=null
&& property.isExpanded
&& property.propertyType==SerializedPropertyType.ObjectReference
&& !property.hasMultipleDifferentValues
? property.objectReferenceValue as ScriptableObject
: null;
if (data)
{
baseHeight += EditorGUIUtility.standardVerticalSpacing * 2;
SerializedObject so = new SerializedObject(data);
SerializedProperty iterator = so.GetIterator();
iterator.NextVisible(true);
var foldoutHeight = 0f;
while (iterator.NextVisible(false))
{
var current = iterator.Copy();
foldoutHeight += EditorGUI.GetPropertyHeight(current, label, true) + EditorGUIUtility.standardVerticalSpacing;
}
baseHeight += Mathf.Max(EditorGUIUtility.singleLineHeight, foldoutHeight);
}
return baseHeight;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
s_CyclicCheck.Clear();
PropertyField(position, property, label);
s_CyclicCheck.Clear();
}
public static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label)
{
Rect propertyFieldRect = PropertyFieldRight(position, property);
EditorGUI.ObjectField(propertyFieldRect, property, objType, label);
PropertyFieldLeft(position, property);
}
public static void ObjectField(Rect position, SerializedProperty property, Type objType)
{
Rect propertyFieldRect = PropertyFieldRight(position, property);
EditorGUI.ObjectField(propertyFieldRect, property, objType);
PropertyFieldLeft(position, property);
}
public static void PropertyField(Rect position, SerializedProperty property, GUIContent label)
{
Rect propertyFieldRect = PropertyFieldRight(position, property);
EditorGUI.PropertyField(propertyFieldRect, property, label, true);
PropertyFieldLeft(position, property);
}
static void PropertyFieldLeft(Rect position, SerializedProperty property)
{
if (property.propertyType==SerializedPropertyType.ObjectReference && property.objectReferenceValue && !property.hasMultipleDifferentValues)
{
DrawScriptableObjectFoldout(position, property);
}
}
static Rect PropertyFieldRight(Rect position, SerializedProperty property)
{
Rect popupWindowRect = new Rect(EditorGUIUtility.GUIToScreenPoint(new Vector2(position.xMin,position.yMin+EditorGUIUtility.singleLineHeight)),
new Vector2(position.width, 500));
int singleButtonWidth = 20;
Rect propertyFieldRect = position;
if (DrawPickAsset(position, property, propertyFieldRect, singleButtonWidth))
{
propertyFieldRect.xMax -= singleButtonWidth;
}
// Draw "Create" for supported assets
if (property.propertyType == SerializedPropertyType.ObjectReference)
{
Rect createBtnRect = new Rect(propertyFieldRect.xMax - singleButtonWidth, position.y, singleButtonWidth, EditorGUIUtility.singleLineHeight);
if (DrawCreateAsset(createBtnRect, property, popupWindowRect))
{
propertyFieldRect.xMax -= singleButtonWidth;
}
}
// Draw "Popout window"
if (!property.hasMultipleDifferentValues && property.propertyType == SerializedPropertyType.ObjectReference)
{
if (property.objectReferenceValue)
{
Rect popoutBtnRect = new Rect(propertyFieldRect.xMax-singleButtonWidth, position.y, singleButtonWidth, EditorGUIUtility.singleLineHeight);
DrawPopoutInspector(popoutBtnRect, property, popupWindowRect);
propertyFieldRect.xMax -= singleButtonWidth;
}
}
return propertyFieldRect;
}
static bool DrawPickAsset(Rect position, SerializedProperty property, Rect propertyFieldRect, int singleButtonWidth)
{
Type propType = property.GetSerializedPropertyType();
var canScenePick = ObjectDrawerPickerTool.CanPickProperty(property);
var canAssetPick = typeof(GameObject).IsAssignableFrom(propType) || typeof(Component).IsAssignableFrom(propType);
Rect buttonRect = new Rect(propertyFieldRect.xMax - singleButtonWidth, position.y, singleButtonWidth, EditorGUIUtility.singleLineHeight);
var wasScenePicking = ObjectDrawerPickerTool.IsPickingFor(property);
var isScenePicking = false;
if (!canScenePick && !canAssetPick)
return false;
// Draw "Picker tool"
if (canScenePick && (!canAssetPick||wasScenePicking))
{
isScenePicking = ImageToggle(buttonRect, ObjectDrawerPickerTool.PickerIcon, wasScenePicking, "Pick from scene");
}
else if (canAssetPick && canScenePick)
{
var options = new []
{
"Eyedrop from scene...",
"Pick from project assets..."
};
var result = ImagePopup(buttonRect, ObjectDrawerPickerTool.PickerIcon, "Pick from scene/project", options);
switch (result)
{
case 0:
isScenePicking = true;
break;
case 1:
DoProjectAssetPick(position, property, propType);
break;
}
}
else
{
if (ImageButton(buttonRect, ObjectDrawerPickerTool.PickerIcon, "Pick from project"))
{
DoProjectAssetPick(position, property, propType);
}
}
if (!wasScenePicking && isScenePicking)
{
ObjectDrawerPickerTool.DoPicker(property);
} else if (!isScenePicking && wasScenePicking)
{
ObjectDrawerPickerTool.Cancel();
}
return true;
}
static void DoProjectAssetPick(Rect position, SerializedProperty property, Type propType)
{
(string path, Type type)[] validAssets;
if (typeof(Component).IsAssignableFrom(propType))
{
if (s_CachedScripts == null)
s_CachedScripts = MonoImporter.GetAllRuntimeMonoScripts();
var validScripts = s_CachedScripts
.Where(x => x && propType.IsAssignableFrom(x.GetClass()))
.ToDictionary(AssetDatabase.GetAssetPath);
if (validScripts.Count > 0)
{
var validScriptPathsSet = new HashSet<string>(validScripts.Keys);
var allPrefabs = AssetDatabase.FindAssets("t:prefab")
.Select(AssetDatabase.GUIDToAssetPath)
.Select(x=>(path:x, dependencies:new HashSet<string>(AssetDatabase.GetDependencies(x,false))))
.ToArray();
EditorUtility.DisplayProgressBar("Prefab lookup search", "Quick search. Won't find built in types. Will be faster on repeat uses", 0.5f);
var basePrefabsSet = new HashSet<string>(allPrefabs.Where(x => validScriptPathsSet.Overlaps(x.dependencies))
.Select(x=>x.path));
while(true)
{
var newVariants = allPrefabs.Where(x => x.dependencies.Overlaps(basePrefabsSet) && !basePrefabsSet.Contains(x.path))
.Select(x => (path: x.path, obj: AssetDatabase.LoadAssetAtPath<GameObject>(x.path)))
.Where(x =>PrefabUtility.IsPartOfVariantPrefab(x.obj) && basePrefabsSet.Contains(AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromOriginalSource(x.obj))))
.Select(x=>x.path)
.ToArray();
if (newVariants.Length == 0)
break;
basePrefabsSet.UnionWith(newVariants);
}
validAssets = basePrefabsSet.Select(AssetDatabase.LoadAssetAtPath<GameObject>)
.SelectMany(x=>x.GetComponents(propType))
.Select(x=>(path:AssetDatabase.GetAssetPath(x), type:x.GetType()))
.ToArray();
// validAssets = AssetDatabase.FindAssets("t:prefab")
// .Select(AssetDatabase.GUIDToAssetPath)
// .Where(x=>validScriptPathsSet.Overlaps(AssetDatabase.GetDependencies(x, false)))
// .Select(AssetDatabase.LoadAssetAtPath<GameObject>)
// .SelectMany(x=>x.GetComponents(propType))
// .Select(x=>(path:AssetDatabase.GetAssetPath(x), type:x.GetType()))
// .ToArray();
EditorUtility.ClearProgressBar();
} else
{
EditorUtility.DisplayProgressBar("Project wide prefab search", "Slower, but finds inbuilt types. Will be faster on repeat uses", 0.5f);
validAssets = AssetDatabase.FindAssets("t:prefab")
.Select(AssetDatabase.GUIDToAssetPath)
.Select(AssetDatabase.LoadAssetAtPath<GameObject>)
.SelectMany(x=>x.GetComponents(propType))
.Select(x=>(path:AssetDatabase.GetAssetPath(x), type:x.GetType()))
.ToArray();
EditorUtility.ClearProgressBar();
}
} else
{
Assert.IsTrue(typeof(GameObject).IsAssignableFrom(propType));
validAssets = AssetDatabase.FindAssets("t:prefab")
.Select(x=>(path:AssetDatabase.GUIDToAssetPath(x), type:typeof(GameObject)))
.ToArray();
}
var guiOptions = validAssets.Select(x => new GUIContent($"{Path.GetFileName(x.path)} ({x.type.Name})", EditorIconUtility.GetIcon(x.type)))
.ToArray();
var callbackProperty = property.Copy();
var callbackSO = callbackProperty.serializedObject;
OptionPopupWindow.Create($"Pick Project asset {propType.Name}",
index =>
{
var selection = validAssets[index];
property.objectReferenceValue = AssetDatabase.LoadAssetAtPath(selection.path, selection.type);
callbackSO.ApplyModifiedProperties();
},
guiOptions,
EditorIconUtility.GetIcon(propType),
"prefab root components only");
}
static void DrawScriptableObjectFoldout(Rect position, SerializedProperty property)
{
ScriptableObject data = !property.hasMultipleDifferentValues
? property.objectReferenceValue as ScriptableObject
: null;
if (!data || !s_CyclicCheck.Add(data))
{
return;
}
Rect foldoutRect = new Rect(position.position,
new Vector2(position.width, EditorGUIUtility.singleLineHeight));
GUI.color = Color.cyan;
property.isExpanded = EditorGUI.Foldout(foldoutRect,
property.isExpanded,
"",
true);
GUI.color = Color.white;
if (property.isExpanded)
{
SerializedObject so = new SerializedObject(data);
int count = 0;
float fullHeight = 0f;
SerializedProperty iterator = so.GetIterator();
iterator.NextVisible(true);
while (iterator.NextVisible(false))
{
float childHeight = EditorGUI.GetPropertyHeight(iterator, new GUIContent(iterator.displayName), true);
fullHeight += childHeight + EditorGUIUtility.standardVerticalSpacing;
++count;
}
fullHeight = Mathf.Max(EditorGUIUtility.singleLineHeight, fullHeight);
var boxRect = new Rect(position.x + EditorGUI.indentLevel * 15f,
position.y + EditorGUIUtility.singleLineHeight,
position.width - EditorGUI.indentLevel * 15f + 2,
Mathf.Max(fullHeight, EditorGUIUtility.singleLineHeight));
GUI.Box(boxRect, "");
if (count == 0)
GUI.Label(boxRect, "No properties");
var prevLabelWidth = EditorGUIUtility.labelWidth;
EditorGUI.BeginChangeCheck();
//using (new EditorGUI.IndentLevelScope())
{
float y = position.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
iterator = so.GetIterator();
iterator.NextVisible(true);
while (iterator.NextVisible(false))
{
var current = iterator.Copy();
float childHeight = EditorGUI.GetPropertyHeight(iterator, new GUIContent(iterator.displayName), true);
Rect childRect = new Rect(position.x + 15, y, position.width - 15, childHeight);
EditorGUI.PropertyField(childRect, current, true);
y += childHeight + EditorGUIUtility.standardVerticalSpacing;
++count;
}
}
if (EditorGUI.EndChangeCheck())
{
so.ApplyModifiedProperties();
}
EditorGUIUtility.labelWidth = prevLabelWidth;
}
s_CyclicCheck.Remove(data);
}
static void DrawPopoutInspector(Rect position, SerializedProperty property, Rect popupWindowRect)
{
if (property.objectReferenceValue != null && !property.hasMultipleDifferentValues)
{
bool wasEnabled = GUI.enabled;
GUI.enabled = true;
if (ImageButton(position, ExpandButton, "Show in popout inspector..."))
{
PopupEditorWindow.Create(property.objectReferenceValue, popupWindowRect);
}
GUI.enabled = wasEnabled;
}
}
static Type[] s_AllTypes;
static Type[] AllTypes => s_AllTypes = s_AllTypes
?? AppDomain.CurrentDomain.GetAssemblies().SelectMany(x =>
{
try
{
return x.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}).ToArray();
static Type s_AssetFileNameExtensionAttributeType;
static Type AssetFileNameExtensionAttributeType => s_AssetFileNameExtensionAttributeType = s_AssetFileNameExtensionAttributeType ?? AllTypes.Where(x => x.Name == "AssetFileNameExtensionAttribute").First();
static PropertyInfo s_AssetFileNameExtensionAttributePreferredInfoPI;
static MonoScript[] s_CachedScripts;
static PropertyInfo AssetFileNameExtensionAttributePreferredInfoPI => s_AssetFileNameExtensionAttributePreferredInfoPI = s_AssetFileNameExtensionAttributePreferredInfoPI ?? AssetFileNameExtensionAttributeType.GetProperty("preferredExtension");
private static bool CanCreateAssetType(Type t)
{
if (t == null)
return false;
if (typeof(ScriptableObject).IsAssignableFrom(t))
{
return GetAssetAttribute(t) != null;
}
return typeof(GameObject).IsAssignableFrom(t) || typeof(Component).IsAssignableFrom(t);
}
private static Attribute GetAssetAttribute(Type t)
{
if (t == null)
return null;
var caa = t.GetCustomAttribute<CreateAssetMenuAttribute>(true);
if (caa!=null)
return caa;
while (t != null)
{
var asf = t.GetCustomAttribute(AssetFileNameExtensionAttributeType,true);
if (asf!=null)
return asf;
t = t.BaseType;
}
return null;
}
private static string GetAssetDisplayName(Type type)
{
if (typeof(ScriptableObject).IsAssignableFrom(type))
{
var attribute = GetAssetAttribute(type);
if (attribute is CreateAssetMenuAttribute caa)
{
return !string.IsNullOrEmpty(caa.menuName)
? caa.menuName.Substring(caa.menuName.LastIndexOf('/') + 1)
: type.Name;
} else if (AssetFileNameExtensionAttributeType.IsAssignableFrom(attribute.GetType()))
{
return type.Name;
}
throw new ArgumentException("Unkown attribute type");
}
return type.Name;
}
private static string GetAssetFileName(Type type)
{
if (typeof(ScriptableObject).IsAssignableFrom(type))
{
var attribute = GetAssetAttribute(type);
if (attribute is CreateAssetMenuAttribute caa)
return caa.fileName;
else if (AssetFileNameExtensionAttributeType.IsAssignableFrom(attribute.GetType()))
{
return null;
}
throw new ArgumentException("Unkown attribute type");
}
return null;
}
private static string GetAssetFileExtension(Type type)
{
if (typeof(ScriptableObject).IsAssignableFrom(type))
{
var attribute = GetAssetAttribute(type);
if (attribute is CreateAssetMenuAttribute caa)
return $"{type.Name}.asset";
else if (AssetFileNameExtensionAttributeType.IsAssignableFrom(attribute.GetType()))
{
return (string)AssetFileNameExtensionAttributePreferredInfoPI.GetValue(attribute);
}
throw new ArgumentException("Unkown attribute type");
}
if (typeof(GameObject).IsAssignableFrom(type))
return "prefab";
else if(typeof(Component).IsAssignableFrom(type))
return $"{type.Name}.prefab";
return null;
}
static bool DrawCreateAsset(Rect position, SerializedProperty property, Rect popupWindowRect)
{
using var scope = new EditorGUI.IndentLevelScope(-EditorGUI.indentLevel);
Type propType = property.GetSerializedPropertyType();
if (propType == null)
{
return false;
}
if (!s_cachedTypes.TryGetValue(propType, out (Type type, string displayName, string fileName, string fileExtension)[] validTypes))
{
var candidates = AllTypes.Where(t => t != null && !t.IsAbstract && propType.IsAssignableFrom(t))
.Where(t=>CanCreateAssetType(t))
.Select(t => (type: t, menuName:GetAssetDisplayName(t), fileName: GetAssetFileName(t), extension:GetAssetFileExtension(t))).ToArray();
s_cachedTypes[propType] = validTypes = candidates.ToArray();
}
if (validTypes.Length == 0)
{
return false;
}
var selection = property.serializedObject.isEditingMultipleObjects || !(property.serializedObject.targetObject is ScriptableObject) || !(typeof(ScriptableObject).IsAssignableFrom(propType))
? (ImageButton(position, NewButton, "New Asset...") ? 0:-1)
: ImagePopup(position, NewButton, "New Asset...", new [] {"New external asset...", "New sub asset..." });
if (selection!=-1)
{
GUIContent[] _options = validTypes.Select(x => (name: x.displayName, icon: EditorIconUtility.GetIcon(x.type)))
.Select(x => new GUIContent(x.name, x.icon))
.ToArray();
Texture2D icon = EditorIconUtility.GetIcon(propType);
var callbackPropery = property.Copy();
switch (selection)
{
case 0:
OptionPopupWindow.Create($"Create External Asset {propType.Name}",
index =>
{
(Type _, string displayName, string fileName, string fileExtension) = validTypes[index];
if (!CreateExternalAssetPopup(callbackPropery, validTypes[index].type, fileName, fileExtension, displayName, out Object instance))
{
return;
}
EditorGUIUtility.PingObject(instance);
SerializedProperty prop = new SerializedObject(property.serializedObject.targetObjects).FindProperty(callbackPropery.propertyPath);
prop.objectReferenceValue = instance;
prop.serializedObject.ApplyModifiedProperties();
},
_options,
icon);
break;
case 1:
OptionPopupWindow.Create($"Create Sub Asset {propType.Name}",
index =>
{
(Type _, string _, string _, string fileExtension) = validTypes[index];
Type type = validTypes[index].type;
Object instance = null;
if (callbackPropery.serializedObject.isEditingMultipleObjects)
return;
var name = callbackPropery.serializedObject.targetObject is Component
? $"{callbackPropery.serializedObject.targetObject.name}.{callbackPropery.GetSanitizedPropertyPath()}"
: $"{callbackPropery.GetSanitizedPropertyPath()}";
TextFieldPopupWindow.Create($"{fileExtension}", defaultValue:name, icon:EditorIconUtility.GetIcon(type), action: value =>
{
instance = CreateSubAssetOfType(type, property.serializedObject.targetObject, $"{value}");
if (!instance)
{
return;
}
EditorGUIUtility.PingObject(instance);
SerializedProperty prop = new SerializedObject(callbackPropery.serializedObject.targetObjects).FindProperty(callbackPropery.propertyPath);
prop.objectReferenceValue = instance;
prop.serializedObject.ApplyModifiedProperties();
});
},
_options,
icon);
break;
}
}
return true;
}
static bool CreateExternalAssetPopup(SerializedProperty property, Type type, string fileName, string fileExtension, string displayName, out Object instance)
{
string filepathPrefix = property.serializedObject.isEditingMultipleObjects
? GetPath(property.serializedObject.targetObject)
: GetLongestCommonPrefix(property.serializedObject.targetObjects
.Select(x => Path.GetDirectoryName(GetPath(x))).ToArray());
string defaultOutputPath = GenerateUniqueAssetPath($"{filepathPrefix}/{property.serializedObject.targetObject.name}");
string defaultName = string.IsNullOrEmpty(fileName)
? Path.GetFileNameWithoutExtension(defaultOutputPath)
: fileName;
var extension = fileExtension;
string filePath = EditorUtility.SaveFilePanel($"Create {displayName}",
$"{filepathPrefix}",
defaultName,
extension);
if (string.IsNullOrEmpty(filePath))
{
instance = null;
return false;
}
filePath = GetRelativePath(Directory.GetParent(Application.dataPath).FullName + Path.DirectorySeparatorChar, filePath);
Object asset;
(asset, instance) = CreateAssetOfType(type, filePath);
return true;
}
static (Object asset, Object instance) CreateAssetOfType(Type type, string filePath)
{
Object asset = null;
Object instance = null;
if (typeof(ScriptableObject).IsAssignableFrom(type))
{
asset = instance = ScriptableObject.CreateInstance(type);
CreateAsset(asset, filePath);
}
else if (typeof(Component).IsAssignableFrom(type))
{
var go = new GameObject(Path.GetFileNameWithoutExtension(filePath),new []{type});
var goAsset = PrefabUtility.SaveAsPrefabAsset(go, filePath);
Object.DestroyImmediate(go);
instance = goAsset.GetComponent(type);
asset = goAsset;
} else if (typeof(GameObject).IsAssignableFrom(type))
{
var go = new GameObject(Path.GetFileNameWithoutExtension(filePath));
var goAsset = PrefabUtility.SaveAsPrefabAsset(go, filePath);
Object.DestroyImmediate(go);
asset = instance = goAsset;
}
return (asset, instance);
}
static Object CreateSubAssetOfType(Type type, Object parentAsset, string assetName)
{
Object instance = null;
if (typeof(ScriptableObject).IsAssignableFrom(type))
{
instance = ScriptableObject.CreateInstance(type);
instance.name = assetName;
AddObjectToAsset(instance, parentAsset);
SaveAssets();
}
return instance;
}
static bool ImageButton(Rect position, Texture2D buttonImg, string tooltip)
{
bool result = GUI.Button(position, new GUIContent("",tooltip));
Vector2 imgSize = new Vector2(buttonImg.width, buttonImg.height);
Rect imgRect = new Rect(position.center - imgSize / 2f, imgSize);
Color prevColor = GUI.color;
GUI.color = EditorGUIUtility.isProSkin ? Color.white : Color.gray;
GUI.DrawTexture(imgRect, buttonImg);
GUI.color = prevColor;
return result;
}
static int ImagePopup(Rect position, Texture2D buttonImg, string tooltip, string[] options)
{
int result = EditorGUI.Popup(position, -1, options,"button");
Vector2 imgSize = new Vector2(buttonImg.width, buttonImg.height);
Rect imgRect = new Rect(position.center - imgSize / 2f, imgSize);
Color prevColor = GUI.color;
GUI.color = EditorGUIUtility.isProSkin ? Color.white : Color.gray;
GUI.DrawTexture(imgRect, buttonImg);
GUI.color = prevColor;
return result;
}
static bool ImageToggle(Rect position, Texture2D buttonImg, bool value, string tooltip)
{
bool result = GUI.Toggle(position, value, new GUIContent("",tooltip), "Button");
Vector2 imgSize = new Vector2(buttonImg.width, buttonImg.height);
Rect imgRect = new Rect(position.center - imgSize / 2f, imgSize);
Color prevColor = GUI.color;
GUI.color = EditorGUIUtility.isProSkin ? Color.white : Color.gray;
GUI.DrawTexture(imgRect, buttonImg);
GUI.color = prevColor;
return result;
}
static string GetPath(Object target)
{
// 1. check for an asset path (ScriptableObject)
string path = GetAssetPath(target);
// 2. check for a prefab path (could be referenced by a monobehaviour)
Object prefab = PrefabUtility.GetCorrespondingObjectFromSource(target);
if (prefab != null && string.IsNullOrEmpty(path))
{
path = GetAssetPath(prefab);
}
// 3. check for a scene path
Component comp = target as Component;
if (comp != null)
{
#if UNITY_2018_3_OR_NEWER
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null && prefabStage.IsPartOfPrefabContents(comp.gameObject))
{
#if UNITY_2020_1_OR_NEWER
path = Path.GetDirectoryName(prefabStage.assetPath)
+ "/" + Path.GetFileNameWithoutExtension(prefabStage.assetPath)
+ "." + comp.gameObject.name + ".obj"; // fake extension as we strip it
#else
path = Path.GetDirectoryName(prefabStage.prefabAssetPath)
+"/"+Path.GetFileNameWithoutExtension(prefabStage.prefabAssetPath)
+"."+comp.gameObject.name+".obj"; // fake extension as we strip it
#endif
} else
#endif
if (!string.IsNullOrEmpty(comp.gameObject.scene.path))
{
path = Path.GetDirectoryName(comp.gameObject.scene.path)
+ "/" + Path.GetFileNameWithoutExtension(comp.gameObject.scene.path)
+ "." + comp.gameObject.name + ".obj"; // fake extension as we strip it
}
}
// 4. give up
if (string.IsNullOrEmpty(path))
{
path = "Assets/" + target.name;
}
return path;
}
static string GetLongestCommonPrefix(string[] s)
{
int k = s[0].Length;
for (int i = 1; i < s.Length; i++)
{
k = Mathf.Min(k, s[i].Length);
for (int j = 0; j < k; j++)
{
if (s[i][j] != s[0][j])
{
k = j;
break;
}
}
}
return s[0].Substring(0, k);
}
/// <summary>
/// Creates a relative path from one file or folder to another.
/// https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path.</returns>
public static string GetRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath))
{
throw new ArgumentNullException("fromPath");
}
if (string.IsNullOrEmpty(toPath))
{
throw new ArgumentNullException("toPath");
}
Uri fromUri = !Path.HasExtension(fromPath) && !fromPath.EndsWith(Path.DirectorySeparatorChar.ToString())
? new Uri($"{fromPath}{Path.DirectorySeparatorChar}")
: new Uri(fromPath);
// Uri toUri = !Path.HasExtension(toPath) && !toPath.EndsWith(Path.DirectorySeparatorChar.ToString())
// ? new Uri($"{fromPath}{Path.DirectorySeparatorChar}")
// : new Uri(toPath);
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme)
{
return toPath;
}
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
}
}
#endif