Skip to content

Instantly share code, notes, and snippets.

@wowbroforce
Last active August 29, 2015 14:19
Show Gist options
  • Save wowbroforce/e78516a62778919742d8 to your computer and use it in GitHub Desktop.
Save wowbroforce/e78516a62778919742d8 to your computer and use it in GitHub Desktop.
Unity editor menu item for creating interface. Place this file into 'Editor' folder.
using UnityEditor;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
public class CreateInterfaceMenuItem {
[MenuItem("Assets/Create/File/Interface...", false, 10)]
private static void CreateInterface() {
var filePath = EditorUtility.SaveFilePanelInProject("Save file", "Interface", "cs", "Enter interface 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 = BuildInterfaceGraph(fileName);
var provider = CodeDomProvider.CreateProvider("CSharp");
provider.GenerateCodeFromCompileUnit(unit, textWriter, new CodeGeneratorOptions());
}
}
}
AssetDatabase.Refresh();
}
private static CodeCompileUnit BuildInterfaceGraph(string interfaceName) {
var codeCompileUnit = new CodeCompileUnit();
var codeNamespace = new CodeNamespace();
codeNamespace.Imports.AddRange(new [] {
new CodeNamespaceImport("UnityEngine"),
new CodeNamespaceImport("System.Collections")
});
codeCompileUnit.Namespaces.Add(codeNamespace);
var declaration = new CodeTypeDeclaration(interfaceName);
declaration.IsInterface = true;
codeNamespace.Types.Add(declaration);
return codeCompileUnit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment