Created
October 21, 2018 20:03
-
-
Save acoppes/a9ec2cefeccfbc6d6cf0b5643ee223d2 to your computer and use it in GitHub Desktop.
Unity menu action to create an empty Editor for the selected MonoScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
using System.Text; | |
using System.IO; | |
public static class CreateCustomEditorAction | |
{ | |
[MenuItem("Assets/Create/Custom Editor from Script", true)] | |
public static bool CreateCustomInspectorValidator() | |
{ | |
return Selection.activeObject is MonoScript; | |
} | |
[MenuItem("Assets/Create/Custom Editor from Script")] | |
public static void CreateCustomInspector() | |
{ | |
// Creates a custom inspector for the given selected MonoScript. | |
var selectedScript = Selection.activeObject as MonoScript; | |
if (selectedScript == null) | |
return; | |
var scriptPath = AssetDatabase.GetAssetPath(selectedScript); | |
if (string.IsNullOrEmpty(scriptPath)) | |
return; | |
var directory = System.IO.Path.GetDirectoryName(scriptPath); | |
var scriptName = System.IO.Path.GetFileNameWithoutExtension(scriptPath); | |
var editorDirectory = System.IO.Path.Combine(directory, "Editor"); | |
if (!System.IO.Directory.Exists(editorDirectory)) | |
{ | |
System.IO.Directory.CreateDirectory(editorDirectory); | |
} | |
var editorScriptName = string.Format("{0}CustomEditor", scriptName); | |
var editorScriptFile = string.Format("{0}.cs", editorScriptName); | |
var editorScriptPath = System.IO.Path.Combine(editorDirectory, editorScriptFile); | |
if (File.Exists(editorScriptPath)) | |
return; | |
var contents = new StringBuilder(); | |
contents.Append("using UnityEngine;\n"); | |
contents.Append("using UnityEditor;\n"); | |
var scriptClass = selectedScript.GetClass(); | |
contents.Append("\n"); | |
contents.AppendFormat("[CustomEditor(typeof({0}))]\n", scriptClass.FullName); | |
contents.AppendFormat("public class {0} : Editor\n", editorScriptName); | |
contents.Append("{\n"); | |
contents.Append("\tpublic override void OnInspectorGUI()\n"); | |
contents.Append("\t{\n"); | |
contents.Append("\t\tDrawDefaultInspector();\n"); | |
contents.Append("\t}\n"); | |
contents.Append("\n"); | |
contents.Append("}\n\n"); | |
System.IO.File.WriteAllText(editorScriptPath, contents.ToString()); | |
AssetDatabase.ImportAsset(editorScriptPath); | |
var editorScript = AssetDatabase.LoadAssetAtPath<MonoScript>(editorScriptPath); | |
EditorGUIUtility.PingObject(editorScript); | |
Selection.activeObject = editorScript; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment