-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericSerializeReferenceFieldAttributeDrawer.cs
213 lines (177 loc) · 9.08 KB
/
GenericSerializeReferenceFieldAttributeDrawer.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
/***
* MIT License
*
* Copyright (c) 2020 TextusGames
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// modified from https://github.com/TextusGames/UnitySerializedReferenceUI/
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace GenericSerializeReference
{
[CustomPropertyDrawer(typeof(GenericSerializeReferenceGeneratedFieldAttribute))]
public class GenericSerializeReferenceFieldAttributeDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, true);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
var labelPosition = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight);
EditorGUI.LabelField(labelPosition, label);
DrawSelectionButtonForManagedReference();
EditorGUI.PropertyField(position, property, GUIContent.none, true);
EditorGUI.EndProperty();
void DrawSelectionButtonForManagedReference()
{
var backgroundColor = new Color(0.1f, 0.55f, 0.9f, 1f);
var buttonPosition = position;
buttonPosition.x += EditorGUIUtility.labelWidth + 1 * EditorGUIUtility.standardVerticalSpacing;
buttonPosition.width = position.width - EditorGUIUtility.labelWidth - 1 * EditorGUIUtility.standardVerticalSpacing;
buttonPosition.height = EditorGUIUtility.singleLineHeight;
var storedIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
var storedColor = GUI.backgroundColor;
GUI.backgroundColor = backgroundColor;
var names = GetSplitNamesFromTypename(property.managedReferenceFullTypename);
var className = string.IsNullOrEmpty(names.ClassName) ? "Null (Assign)" : names.ClassName;
className = className.Split('/').Last();
var assemblyName = names.AssemblyName;
if (GUI.Button(buttonPosition, new GUIContent(className, className + " ( "+ assemblyName +" )" )))
ShowContextMenuForManagedReference();
GUI.backgroundColor = storedColor;
EditorGUI.indentLevel = storedIndent;
}
(string AssemblyName, string ClassName) GetSplitNamesFromTypename(string typename)
{
if (string.IsNullOrEmpty(typename))
return ("","");
var typeSplitString = typename.Split(char.Parse(" "));
var typeClassName = typeSplitString[1];
var typeAssemblyName = typeSplitString[0];
return (typeAssemblyName, typeClassName);
}
void ShowContextMenuForManagedReference()
{
var context = new GenericMenu();
FillContextMenu(context);
context.ShowAsContext();
}
void FillContextMenu(GenericMenu contextMenu)
{
// Adds "Make Null" menu command
contextMenu.AddItem(new GUIContent("Null"), false, SetManagedReferenceToNull());
// Collects appropriate types
var appropriateTypes = GetAppropriateTypesForAssigningToManagedReference();
// Adds appropriate types to menu
foreach (var appropriateType in appropriateTypes)
AddItemToContextMenu(appropriateType, contextMenu);
}
GenericMenu.MenuFunction SetManagedReferenceToNull()
{
return () =>
{
property.serializedObject.Update();
property.managedReferenceValue = null;
property.serializedObject.ApplyModifiedProperties();
};
}
void AddItemToContextMenu(Type type, GenericMenu genericMenuContext)
{
// it must have a BaseType
var assemblyName = type.BaseType.Assembly.ToString().Split('(', ',')[0];
var entryName = type.BaseType.ToReadableName() + " ( " + assemblyName + " )";
genericMenuContext.AddItem(new GUIContent(entryName), false, AssignNewInstanceCommand, new GenericMenuParameterForAssignInstanceCommand(type, property));
}
void AssignNewInstanceCommand(object objectGenericMenuParameter )
{
var parameter = (GenericMenuParameterForAssignInstanceCommand) objectGenericMenuParameter;
var type = parameter.Type;
var property = parameter.Property;
AssignNewInstanceOfTypeToManagedReference(property, type);
}
object AssignNewInstanceOfTypeToManagedReference(SerializedProperty serializedProperty, Type type)
{
var instance = Activator.CreateInstance(type);
serializedProperty.serializedObject.Update();
serializedProperty.managedReferenceValue = instance;
serializedProperty.serializedObject.ApplyModifiedProperties();
return instance;
}
IEnumerable<Type> GetAppropriateTypesForAssigningToManagedReference()
{
var fieldType = GetManagedReferenceFieldType();
return GetAppropriateTypesForAssigningToManagedReferenceOfField(fieldType);
}
// Gets real type of managed reference
Type GetManagedReferenceFieldType()
{
var realPropertyType = GetRealTypeFromTypename(property.managedReferenceFieldTypename);
if (realPropertyType != null)
return realPropertyType;
Debug.LogError($"Can not get field type of managed reference : {property.managedReferenceFieldTypename}");
return null;
}
// Gets real type of managed reference's field typeName
Type GetRealTypeFromTypename(string stringType)
{
var names = GetSplitNamesFromTypename(stringType);
var realType = Type.GetType($"{names.ClassName}, {names.AssemblyName}");
return realType;
}
IEnumerable<Type> GetAppropriateTypesForAssigningToManagedReferenceOfField(Type fieldType)
{
var appropriateTypes = new List<Type>();
var propertyType = ((GenericSerializeReferenceGeneratedFieldAttribute) this.attribute).PropertyType;
// Get and filter all appropriate types
var derivedTypes = TypeCache.GetTypesDerivedFrom(fieldType).Intersect(TypeCache.GetTypesDerivedFrom(propertyType));
foreach (var type in derivedTypes)
{
// Skips unity engine Objects (because they are not serialized by SerializeReference)
if (type.IsSubclassOf(typeof(UnityEngine.Object)))
continue;
// Skip abstract classes because they should not be instantiated
if (type.IsAbstract)
continue;
// Skip types that has no public empty constructors (activator can not create them)
if (type.IsClass && type.GetConstructor(Type.EmptyTypes) == null) // Structs still can be created (strangely)
continue;
appropriateTypes.Add(type);
}
return appropriateTypes;
}
}
private readonly struct GenericMenuParameterForAssignInstanceCommand
{
public GenericMenuParameterForAssignInstanceCommand(Type type, SerializedProperty property)
{
Type = type;
Property = property;
}
public readonly SerializedProperty Property;
public readonly Type Type;
}
}
}