-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMonoScriptIconInspector.cs
113 lines (88 loc) · 2.82 KB
/
MonoScriptIconInspector.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
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace cmdwtf.UnityTools.Editor
{
[CustomEditor(typeof(MonoScript))]
[CanEditMultipleObjects]
public class MonoScriptIconInspector : UnityEditor.Editor
{
private UnityEditor.Editor _fallbackEditor;
private Type _fallbackEditorType;
private SerializedProperty _iconProperty;
private void OnEnable()
{
Assembly asm = typeof(UnityEditor.Editor).Assembly;
_fallbackEditorType = asm.GetType($"{nameof(UnityEditor)}.MonoScriptInspector") ??
asm.GetType($"{nameof(UnityEditor)}.GenericInspector");
if (_fallbackEditorType != null)
{
_fallbackEditor = CreateEditor(targets, _fallbackEditorType);
}
if (_fallbackEditor == null || _fallbackEditorType == null)
{
Debug.LogWarning("Failed to create fallback editor, couldn't find expected types.");
}
_iconProperty = serializedObject.FindProperty("m_Icon");
}
private void OnDisable()
{
if (_fallbackEditor != null)
{
DestroyImmediate(_fallbackEditor);
}
_fallbackEditor = null;
}
public override void OnInspectorGUI()
{
EditorGUILayout.BeginHorizontal();
serializedObject.UpdateIfRequiredOrScript();
GUIContent iconGuiContent = new("Script Icon", "The icon to set for the script.");
GUIContent clearIconContent = new("Clear Icon", "Remove the assigned icon from the script.");
EditorGUILayout.PropertyField(_iconProperty, iconGuiContent, GUILayout.ExpandWidth(true));
if (GUILayout.Button("Apply", GUILayout.ExpandWidth(false)))
{
SetIconOnTargets(_iconProperty.objectReferenceValue as Texture2D);
}
if (EditorGUILayoutEx.InlineHamburgerMenuButton())
{
GenericMenu menu = new();
if (_iconProperty.objectReferenceValue != null)
{
menu.AddItem(clearIconContent, false, () => SetIconOnTargets(null));
}
else
{
menu.AddDisabledItem(clearIconContent, false);
}
menu.ShowAsContext();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space(EditorGUIUtility.standardVerticalSpacing);
if (_fallbackEditor != null)
{
_fallbackEditor.OnInspectorGUI();
}
}
private void SetIconOnTargets(Texture2D iconTexture)
{
foreach (Object t in targets)
{
if (t is not MonoScript ms)
{
Debug.LogWarning($"Target object is {t.GetType().FullName}, not {nameof(MonoScript)}, can't assign icon.");
continue;
}
if (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ms)) is not MonoImporter importer)
{
Debug.LogWarning($"Failed to get importer for {ms.name}.");
continue;
}
importer.SetIcon(iconTexture);
importer.SaveAndReimport();
}
}
}
}