Unity编辑器拓展,从自定义脚本模板创建脚本

效果图

在这里插入图片描述
在这里插入图片描述

准备模板

  • 将模板文件放到特定目录 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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值