Skip to content

Instantly share code, notes, and snippets.

@wowbroforce
Last active August 29, 2015 14:19
Show Gist options
  • Save wowbroforce/5a8fe5d9bc4b67619625 to your computer and use it in GitHub Desktop.
Save wowbroforce/5a8fe5d9bc4b67619625 to your computer and use it in GitHub Desktop.
Unity editor menu item for creating MonoBehaviour subclass. Place this file into 'Editor' folder.
using UnityEditor;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
public class CreateMonoBehaviourSubclassMenuItem {
[MenuItem("Assets/Create/File/MonoBehaviour Subclass...", false, 11)]
private static void CreateMonoBehaviourClass() {
var filePath = EditorUtility.SaveFilePanelInProject("Save file", "MonoBehaviourSubclass", "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 = BuildMonoBehaviourSubclassGraph(fileName);
var provider = CodeDomProvider.CreateProvider("CSharp");
provider.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions());
}
}
}
AssetDatabase.Refresh();
}
private static CodeCompileUnit BuildMonoBehaviourSubclassGraph(string className) {
var unit = new CodeCompileUnit();
var @namespace = new CodeNamespace();
unit.Namespaces.Add(@namespace);
@namespace.Imports.AddRange(new [] {
new CodeNamespaceImport("UnityEngine"),
new CodeNamespaceImport("System.Collections")
});
var declaration = new CodeTypeDeclaration { Name = className };
@namespace.Types.Add(declaration);
declaration.BaseTypes.Add(new CodeTypeReference { BaseType = "MonoBehaviour" });
declaration.Members.Add(new CodeMemberField {
Name = "_transform",
Type = new CodeTypeReference("Transform")
});
var methodAwake = new CodeMemberMethod { Name = "Awake" };
methodAwake.Statements.Add(new CodeSnippetStatement("\t\t_transform = GetComponent<Transform>();"));
declaration.Members.AddRange(new [] {
methodAwake,
new CodeMemberMethod { Name = "OnEnable" },
new CodeMemberMethod { Name = "Start" },
new CodeMemberMethod { Name = "Update" },
new CodeMemberMethod { Name = "FixedUpdate" },
new CodeMemberMethod { Name = "OnDisable" }
});
return unit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment