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));
        }
    }
}
相关推荐
ghost1431 小时前
C#学习第29天:表达式树(Expression Trees)
开发语言·c#
安木夕11 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
FakeOccupational14 小时前
【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统
网络·游戏
gregmankiw14 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
XR-AI-JK14 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
阿蒙Amon15 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
钢铁男儿18 小时前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群19 小时前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o19 小时前
63、.NET 异常处理
c#·.net·异常处理
从零开始学习人工智能21 小时前
从游戏到自动驾驶:互联网时代强化学习如何让机器学会自主决策?
人工智能·游戏·自动驾驶