效果图
准备模板
- 将模板文件放到特定目录 Editor Default Resources
- 该目录仅Editor下被使用,不会被包含到运行时
代码
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
public class ScriptCreatorWindow : EditorWindow
{
//priority is lesser position is more frontal
// [MenuItem("Assets/Create/c# Script ex",false, 1000)]
[MenuItem("Assets/Create/c# Script ex", false, 1)]
public static void ShowWindow()
{
var window = EditorWindow.GetWindow(typeof(ScriptCreatorWindow));
var screenResolution = Screen.currentResolution;
//left,top to center,center
var w = 300;
var h = 150;
var r = new Rect(screenResolution.width * 0.5f - w * 0.5f, screenResolution.height * 0.5f - h * 0.5f, w, h);
window.position = r;
}
private string scriptName;
void OnGUI()
{
GUILayout.Label("Base Settings", EditorStyles.boldLabel);
scriptName = EditorGUILayout.TextField("Name", scriptName);
if (string.IsNullOrEmpty(scriptName))
{
scriptName = "Template";
}
// EditorGUILayout.
//EditorGUI.
if (GUILayout.Button("Create"))
{
Create();
Close();
}
}
void Create()
{
var templateSource = EditorGUIUtility.Load("DC/Template.bytes") as TextAsset;
if (templateSource == null)
{
Debug.Log("no template file");
return;
}
string codeSrc = templateSource.text;
if (string.IsNullOrEmpty(codeSrc))
{
Debug.Log("no template content");
return;
}
codeSrc = templateSource.text.Replace("_ClsName", scriptName);
var assetPath = string.Format("{0}/{1}{2}", GetSelectedPathOrFallback(), scriptName, ".cs");
var filePath = Application.dataPath.Replace("Assets", assetPath);
File.WriteAllText(filePath, codeSrc);
AssetDatabase.ImportAsset(assetPath);
}
public static string GetSelectedPathOrFallback()
{
string path = "Assets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
{
path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
//如果是目录获得目录名,如果是文件获得文件所在的目录名
path = Path.GetDirectoryName(path);
break;
}
}
return path;
}
}