Skip to content

Instantly share code, notes, and snippets.

@wowbroforce
Last active August 29, 2015 14:19
Show Gist options
  • Save wowbroforce/6dfe765123d4b741cba0 to your computer and use it in GitHub Desktop.
Save wowbroforce/6dfe765123d4b741cba0 to your computer and use it in GitHub Desktop.
Unity editor menu item for creating EditorWindow subclass. Place this file into 'Editor' folder.
using UnityEditor;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
public class CreateEditorWindowSubclassMenuItem {
[MenuItem("Assets/Create/File/EditorWindow Subclass...", false, 12)]
private static void CreateEditorWindowClass() {
var filePath = EditorUtility.SaveFilePanelInProject("Save file", "EditorWindowSubclass", "cs", "Enter class name");
if (!string.IsNullOrEmpty(filePath)) {
using (var streamWriter = new StreamWriter(File.Create(filePath))) {
using (var tw = new IndentedTextWriter(streamWriter, " ")) {
var fileName = Path.GetFileNameWithoutExtension(filePath);
var unit = BuildEditorWindowSubclassUnit(fileName);
var provider = CodeDomProvider.CreateProvider("CSharp");
provider.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions());
}
}
}
AssetDatabase.Refresh();
}
private static CodeCompileUnit BuildEditorWindowSubclassUnit(string className) {
var unit = new CodeCompileUnit();
var @namespace = new CodeNamespace();
unit.Namespaces.Add(@namespace);
@namespace.Imports.Add(new CodeNamespaceImport("UnityEngine"));
@namespace.Imports.Add(new CodeNamespaceImport("UnityEditor"));
@namespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
var declaration = new CodeTypeDeclaration { Name = className };
@namespace.Types.Add(declaration);
declaration.BaseTypes.Add(new CodeTypeReference { BaseType = "EditorWindow" });
var methodAwake = new CodeMemberMethod {
Name = "Init",
Attributes = MemberAttributes.Static
};
methodAwake.Statements.Add(new CodeVariableDeclarationStatement(className, "window"));
methodAwake.Statements.Add(
new CodeAssignStatement(
new CodeVariableReferenceExpression("window"),
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
null,
"CreateInstance",
new CodeTypeReference(className)
)
)
)
);
methodAwake.Statements.Add(
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeVariableReferenceExpression("window"),
"Show"
)
)
)
);
declaration.Members.Add(methodAwake);
declaration.Members.Add(new CodeMemberMethod { Name = "OnGUI" });
return unit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment