推荐阅读

一、前言

有些代码,会在代码的头部写上一大堆的注释:
(1)说明这是谁写的
(2)什么时候创建的
(3)什么版本
(4)什么作用
(5)版本变更时间

这样就可以很清晰的看到这个脚本是谁写的,写了什么,变更的时间版本等,利于开发。

总是总是写一个脚本,复制过去,改一下,也感觉有些繁琐。

接下来就教大家如何自动为脚本添加头注。

二、实现

using System.IO;

namespace Editor
{
    /// <summary>
    /// 创建脚本自动添加头注
    /// </summary>
    public class FirstComment : UnityEditor.AssetModificationProcessor
    {
        /// <summary>
        /// 在资源创建生成.meta时调用
        /// </summary>
        /// <param name="path">自动传入资源路径</param>
        public static void OnWillCreateAsset(string path)
        {
            path = path.Replace(".meta", "");
            if (!path.EndsWith(".cs")) return;
            string allText = "// ========================================================\r\n"
                             + "// 描述:\r\n"
                             + "// 功能:\r\n"
                             + "// 作者:XXX \r\n"
                             + "// 创建时间:#CreateTime#\r\n"
                             + "// 版本:1.0\r\n"
                             + "// 变更时间:\r\n"
                             + "// 变更版本:#CreateTime2#\r\n"
                             + "// 脚本路径:#ScripsPath#\r\n"
                             + "// ========================================================\r\n";
            allText += File.ReadAllText(path);
            allText =  allText.Replace("#CreateTime#", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            allText = allText.Replace("#ScripsPath#", path);
            File.WriteAllText(path, allText);
        }
    }
}

效果图:
【Unity日常开发】创建脚本自动添加头注_个人博客