自定义C#脚本模板

第一步:在Editor文件夹下创建ScriptTemplates文件夹,然后在该文件夹下创建myScript.cs.txt文件,在该文件里面写模板
第二步:在Editor文件下创建一个C#脚本(Script_04_01 ),该脚本内容为:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;

public class Script_04_01 
{
   
   private const string MY_SCRIPT_DEFAULT = "Assets/Editor/ScriptTemplates/myScript.cs.txt";//脚本模板所在的目录

   [MenuItem("Assets/Create/myScript", false, 0)]
   public static void CreateMyScript()
   {
      string locationPath = GetSelectedPathOrFallback();//返回路径
      ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
            ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(),
            locationPath+"/myScript.cs",
            null,
            MY_SCRIPT_DEFAULT
         );
   }

   private 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;
   }
}

public class MyDoCreateScriptAsset: EndNameEditAction
{
   public override void Action(int instanceId, string pathName, string resourceFile)
   {
      UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
      ProjectWindowUtil.ShowCreatedAsset(o);
   }

   internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
   {
      string fullPath = Path.GetFullPath(pathName);
      
      StreamReader streamReader = new StreamReader(resourceFile);
      string text = streamReader.ReadToEnd();
      streamReader.Close();
      //获得用户输入文件名
      string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
      //替换文件名
      text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
      
      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);
      return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
   }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值