Skip to content

Instantly share code, notes, and snippets.

@fumobox
Created November 18, 2017 13:06
Show Gist options
  • Save fumobox/fbc42b9c1aad632092a2b9ce16c1c408 to your computer and use it in GitHub Desktop.
Save fumobox/fbc42b9c1aad632092a2b9ce16c1c408 to your computer and use it in GitHub Desktop.
Simple class generator for Unity
using UnityEditor;
using UnityEngine;
using System.IO;
namespace MPF.Editor
{
public class TemplateGenerator: EditorWindow
{
readonly string GeneralTemplate =
"using System.Collections;" + System.Environment.NewLine +
"using System.Collections.Generic;" + System.Environment.NewLine +
"using UnityEngine;" + System.Environment.NewLine + System.Environment.NewLine +
"namespace {0}" + System.Environment.NewLine +
"{{" + System.Environment.NewLine +
" public class {1}" + System.Environment.NewLine +
" {{" + System.Environment.NewLine +
" }}" + System.Environment.NewLine +
"}}";
string namespaceName = "MPFTemplate";
string className = "MPFClass";
[MenuItem("MPF/Template")]
public static void CreateGeneralTemplate()
{
EditorWindow.GetWindow<TemplateGenerator>("Template");
}
void OnGUI()
{
namespaceName = EditorGUILayout.TextField("Namespace", namespaceName);
className = EditorGUILayout.TextField("Class", className);
if (GUILayout.Button("Generate"))
{
string path = FileManager.FormatPath(Path.Combine(Application.dataPath, className + ".cs"));
Debug.Log("Generate file: " + path);
if(File.Exists(path))
{
EditorUtility.DisplayDialog("Error", "File already exists." + System.Environment.NewLine + path, "OK");
return;
}
if (string.IsNullOrEmpty(namespaceName))
{
EditorUtility.DisplayDialog("Error", "Namespace is empty.", "OK");
return;
}
if (string.IsNullOrEmpty(className))
{
EditorUtility.DisplayDialog("Error", "Class name is empty.", "OK");
return;
}
var fs = File.Create(path);
var sw = new StreamWriter(fs);
sw.Write(string.Format(GeneralTemplate, namespaceName, className));
sw.Close();
fs.Close();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment