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
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace XNodeEditor {
/// <summary> A set of editor-only utilities and extensions for xNode </summary>
public static class NodeEditorUtilities {
/// <summary>C#'s Script Icon [The one MonoBhevaiour Scripts have].</summary>
private static Texture2D scriptIcon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D);
/// Saves Attribute from Type+Field for faster lookup. Resets on recompiles.
private static Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>> typeAttributes = new Dictionary<Type, Dictionary<string, Dictionary<Type, Attribute>>>();
/// Saves ordered PropertyAttribute from Type+Field for faster lookup. Resets on recompiles.
private static Dictionary<Type, Dictionary<string, List<PropertyAttribute>>> typeOrderedPropertyAttributes = new Dictionary<Type, Dictionary<string, List<PropertyAttribute>>>();
public static bool GetAttrib<T>(Type classType, out T attribOut) where T : Attribute {
object[] attribs = classType.GetCustomAttributes(typeof(T), false);
return GetAttrib(attribs, out attribOut);
}
public static bool GetAttrib<T>(object[] attribs, out T attribOut) where T : Attribute {
for (int i = 0; i < attribs.Length; i++) {
if (attribs[i] is T) {
attribOut = attribs[i] as T;
return true;
}
}
attribOut = null;
return false;
}
public static bool GetAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute {
// If we can't find field in the first run, it's probably a private field in a base class.
FieldInfo field = classType.GetFieldInfo(fieldName);
// This shouldn't happen. Ever.
if (field == null) {
Debug.LogWarning("Field " + fieldName + " couldnt be found");
attribOut = null;
return false;
}
object[] attribs = field.GetCustomAttributes(typeof(T), true);
return GetAttrib(attribs, out attribOut);
}
public static bool HasAttrib<T>(object[] attribs) where T : Attribute {
for (int i = 0; i < attribs.Length; i++) {
if (attribs[i].GetType() == typeof(T)) {
return true;
}
}
return false;
}
public static bool GetCachedAttrib<T>(Type classType, string fieldName, out T attribOut) where T : Attribute {
Dictionary<string, Dictionary<Type, Attribute>> typeFields;
if (!typeAttributes.TryGetValue(classType, out typeFields)) {
typeFields = new Dictionary<string, Dictionary<Type, Attribute>>();
typeAttributes.Add(classType, typeFields);
}
Dictionary<Type, Attribute> typeTypes;
if (!typeFields.TryGetValue(fieldName, out typeTypes)) {
typeTypes = new Dictionary<Type, Attribute>();
typeFields.Add(fieldName, typeTypes);
}
Attribute attr;
if (!typeTypes.TryGetValue(typeof(T), out attr)) {
if (GetAttrib<T>(classType, fieldName, out attribOut)) {
typeTypes.Add(typeof(T), attribOut);
return true;
} else typeTypes.Add(typeof(T), null);
}
if (attr == null) {
attribOut = null;
return false;
}
attribOut = attr as T;
return true;
}
public static List<PropertyAttribute> GetCachedPropertyAttribs(Type classType, string fieldName) {
Dictionary<string, List<PropertyAttribute>> typeFields;
if (!typeOrderedPropertyAttributes.TryGetValue(classType, out typeFields)) {
typeFields = new Dictionary<string, List<PropertyAttribute>>();
typeOrderedPropertyAttributes.Add(classType, typeFields);
}
List<PropertyAttribute> typeAttributes;
if (!typeFields.TryGetValue(fieldName, out typeAttributes)) {
FieldInfo field = classType.GetFieldInfo(fieldName);
object[] attribs = field.GetCustomAttributes(typeof(PropertyAttribute), true);
typeAttributes = attribs.Cast<PropertyAttribute>().Reverse().ToList(); //Unity draws them in reverse
typeFields.Add(fieldName, typeAttributes);
}
return typeAttributes;
}
public static bool IsMac() {
#if UNITY_2017_1_OR_NEWER
return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX;
#else
return SystemInfo.operatingSystem.StartsWith("Mac");
#endif
}
/// <summary> Returns true if this can be casted to <see cref="Type"/></summary>
public static bool IsCastableTo(this Type from, Type to) {
if (to.IsAssignableFrom(from)) return true;
var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(
m => m.ReturnType == to &&
(m.Name == "op_Implicit" ||
m.Name == "op_Explicit")
);
return methods.Count() > 0;
}
/// <summary> Return a prettiefied type name. </summary>
public static string PrettyName(this Type type) {
if (type == null) return "null";
if (type == typeof(System.Object)) return "object";
if (type == typeof(float)) return "float";
else if (type == typeof(int)) return "int";
else if (type == typeof(long)) return "long";
else if (type == typeof(double)) return "double";
else if (type == typeof(string)) return "string";
else if (type == typeof(bool)) return "bool";
else if (type.IsGenericType) {
string s = "";
Type genericType = type.GetGenericTypeDefinition();
if (genericType == typeof(List<>)) s = "List";
else s = type.GetGenericTypeDefinition().ToString();
Type[] types = type.GetGenericArguments();
string[] stypes = new string[types.Length];
for (int i = 0; i < types.Length; i++) {
stypes[i] = types[i].PrettyName();
}
return s + "<" + string.Join(", ", stypes) + ">";
} else if (type.IsArray) {
string rank = "";
for (int i = 1; i < type.GetArrayRank(); i++) {
rank += ",";
}
Type elementType = type.GetElementType();
if (!elementType.IsArray) return elementType.PrettyName() + "[" + rank + "]";
else {
string s = elementType.PrettyName();
int i = s.IndexOf('[');
return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i);
}
} else return type.ToString();
}
/// <summary> Returns the default name for the node type. </summary>
public static string NodeDefaultName(Type type) {
string typeName = type.Name;
// Automatically remove redundant 'Node' postfix
if (typeName.EndsWith("Node")) typeName = typeName.Substring(0, typeName.LastIndexOf("Node"));
typeName = UnityEditor.ObjectNames.NicifyVariableName(typeName);
return typeName;
}
/// <summary> Returns the default creation path for the node type. </summary>
public static string NodeDefaultPath(Type type) {
string typePath = type.ToString().Replace('.', '/');
// Automatically remove redundant 'Node' postfix
if (typePath.EndsWith("Node")) typePath = typePath.Substring(0, typePath.LastIndexOf("Node"));
typePath = UnityEditor.ObjectNames.NicifyVariableName(typePath);
return typePath;
}
/// <summary>Creates a new C# Class.</summary>
[MenuItem("Assets/Create/xNode/Node C# Script", false, 89)]
private static void CreateNode() {
string[] guids = AssetDatabase.FindAssets("xNode_NodeTemplate.cs");
if (guids.Length == 0) {
Debug.LogWarning("xNode_NodeTemplate.cs.txt not found in asset database");
return;
}
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
CreateFromTemplate(
"NewNode.cs",
path
);
}
/// <summary>Creates a new C# Class.</summary>
[MenuItem("Assets/Create/xNode/NodeGraph C# Script", false, 89)]
private static void CreateGraph() {
string[] guids = AssetDatabase.FindAssets("xNode_NodeGraphTemplate.cs");
if (guids.Length == 0) {
Debug.LogWarning("xNode_NodeGraphTemplate.cs.txt not found in asset database");
return;
}
string path = AssetDatabase.GUIDToAssetPath(guids[0]);
CreateFromTemplate(
"NewNodeGraph.cs",
path
);
}
public static void CreateFromTemplate(string initialName, string templatePath) {
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
0,
ScriptableObject.CreateInstance<DoCreateCodeFile>(),
initialName,
scriptIcon,
templatePath
);
}
/// Inherits from EndNameAction, must override EndNameAction.Action
public class DoCreateCodeFile : UnityEditor.ProjectWindowCallback.EndNameEditAction {
public override void Action(int instanceId, string pathName, string resourceFile) {
Object o = CreateScript(pathName, resourceFile);
ProjectWindowUtil.ShowCreatedAsset(o);
}
}
/// <summary>Creates Script from Template's path.</summary>
internal static UnityEngine.Object CreateScript(string pathName, string templatePath) {
string className = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
string templateText = string.Empty;
UTF8Encoding encoding = new UTF8Encoding(true, false);
if (File.Exists(templatePath)) {
/// Read procedures.
StreamReader reader = new StreamReader(templatePath);
templateText = reader.ReadToEnd();
reader.Close();
templateText = templateText.Replace("#SCRIPTNAME#", className);
templateText = templateText.Replace("#NOTRIM#", string.Empty);
/// You can replace as many tags you make on your templates, just repeat Replace function
/// e.g.:
/// templateText = templateText.Replace("#NEWTAG#", "MyText");
/// Write procedures.
StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
writer.Write(templateText);
writer.Close();
AssetDatabase.ImportAsset(pathName);
return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
} else {
Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
return null;
}
}
}
}
|