Unity3D 自定义格式化创建模板+编辑器命名

csharp 复制代码
        [MenuItem("Assets/Create/Format/Unit Script", false, 0)]
        public static void CreateUnitScript()
        {
            FileCreateHelper.CreateScriptWithTitle(@$"
using System;
using System.Collections;
using System.Collections.Generic;
using AirFramework;

namespace {FrameworkSettings.instance.defaultNamespace}
{{
    public class #NAME# : Unit
    {{
        protected override void OnDispose()
        {{
            
        }}
    }}
}}

");
        }
csharp 复制代码
public static void CreateScript(string source, string defaultName = "NewScript.cs", Texture2D icon = null)
        {
            //开始编辑名字的操作
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
            ScriptableObject.CreateInstance<CreateScriptAsset>(),
            $"{FileCreateHelper.GetSelectedPathOrFallback()}/{defaultName}",
            icon, source
           );
        }
csharp 复制代码
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;

namespace AirFrameworkEditor
{
    //用于创建文本
    class CreateScriptAsset : EndNameEditAction
    {
        public override void Action(int instanceId, string pathName, string sourceCode)
        {
            UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, sourceCode);
            ProjectWindowUtil.ShowCreatedAsset(o);
        }

        internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
        {
            string fullPath = Path.GetFullPath(pathName);

            string text = resourceFile;

            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName).Split('.')[0];
            text = text.Replace("#NAME#", fileNameWithoutExtension.Replace(" ", string.Empty));

            bool encoderShouldEmitUTF8Identifier = true;
            bool throwOnInvalidBytes = false;
            UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
            bool append = false;
            StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
            streamWriter.Write(text);
            streamWriter.Close();

            AssetDatabase.ImportAsset(pathName);
            AssetDatabase.Refresh();
            return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
        }
    }
}
相关推荐
hez20105 小时前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
金銀銅鐵3 天前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏
金銀銅鐵4 天前
借助 Pygame 探索最大公约数的规律
python·数学·游戏
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
nujnewnehc8 天前
不会 py, 用 ai 写了个游戏辅助的感受
人工智能·游戏
小码编匠8 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net