Unity 给脚本自动添加头部注释

Unity 给脚本自动添加头部注释

在一些公司需要代码严格的管理,有时候会需要用到每个脚本的头部做一些介绍,用下面的方法可以帮你解决这个问题

1.在工程面板中建一个Editor文件夹

Unity 给脚本自动添加头部注释

2.新建一个ChangeScriptTemplates 脚本,加入下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using System;  
using System.IO;  
    
public class ChangeScriptTemplates : UnityEditor.AssetModificationProcessor {  
    
    // 要添加的注释的内容  
    private static string annotationStr =  
        "// ========================== \r\n"  
        "// 描述:\r\n"  
        "// 作者:\r\n"  
        "// 创建时间:#CreateTime# \r\n"  
        "// 版本:\r\n"  
        "// ========================== \r\n\n";  
    
    public static void OnWillCreateAsset(string path)  
    {  
        // 排除“.meta”文件  
        path = path.Replace(".meta""");  
        // 如果是CS脚本,则进行添加注释处理  
        if (path.EndsWith(".cs"))  
        {  
            // 读取cs脚本的内容并添加到annotationStr 后面  
            annotationStr += File.ReadAllText(path);  
            // 把 #CreateTime# 替换成具体创建时间  
            annotationStr = annotationStr.Replace("#CreateTime#", System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));  
            // 把内容重新写入脚本  
            File.WriteAllText(path, annotationStr);  
        }  
    }  
}

3.再次新建脚本,成功


欢迎加QQ群 438977783 进行交流