Skip to content

Instantly share code, notes, and snippets.

@wowbroforce
Last active August 29, 2015 14:19
Show Gist options
  • Save wowbroforce/4f445f26481d1c3078e0 to your computer and use it in GitHub Desktop.
Save wowbroforce/4f445f26481d1c3078e0 to your computer and use it in GitHub Desktop.
Unity editor menu item for creating simple class. Place this file into 'Editor' folder.
using UnityEditor;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
public class CreateClassMenuItem {
[MenuItem("Assets/Create/File/Class...", false, 13)]
private static void CreateClass() {
var filePath = EditorUtility.SaveFilePanelInProject("Save file", "Class", "cs", "Enter class name");
if (!string.IsNullOrEmpty(filePath)) {
using (var streamWriter = new StreamWriter(File.Create(filePath))) {
using (var textWriter = new IndentedTextWriter(streamWriter, " ")) {
var fileName = Path.GetFileNameWithoutExtension(filePath);
var unit = BuildClassUnit(fileName);
var provider = CodeDomProvider.CreateProvider("CSharp");
provider.GenerateCodeFromCompileUnit(unit, textWriter, new CodeGeneratorOptions());
}
}
}
AssetDatabase.Refresh();
}
private static CodeCompileUnit BuildClassUnit(string className) {
var unit = new CodeCompileUnit();
var @namespace = new CodeNamespace();
@namespace.Imports.AddRange(new [] {
new CodeNamespaceImport { Namespace = "UnityEngine" },
new CodeNamespaceImport { Namespace = "System.Collections" }
});
unit.Namespaces.Add(@namespace);
var declaration = new CodeTypeDeclaration {
Name = className,
IsClass = true
};
@namespace.Types.Add(declaration);
return unit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment