在做团队开发时,往往需要在脚本顶部加入作者,时间等的注释。而每次创建脚本自己添加麻烦,所以这里做一个自动添加顶头注释功能
网上有很多种方法,我这里总结了两种
第一种:
在Editor文件下创建脚本AddFileHaed
下面贴代码:
public class AddFileHead : UnityEditor.AssetModificationProcessor
{
private static string headNotes =
"/**************************************\r\n" +
"*FileName:#FileName#\r\n" +
"*Author:\r\n"+
"*Version:#Version#\r\n" +
"*Date:#DATE#\r\n" +
"*Description:\r\n"+
"*History:\r\n"+
"**************************************/\r\n";
public static void OnWillCreateAsset(string _newFile)
{
_newFile = _newFile.Replace(".meta", "");
if (!_newFile.EndsWith(".cs")) return;
headNotes += File.ReadAllText(_newFile);
headNotes = headNotes.Replace("#FileName#", Path.GetFileName(_newFile));
headNotes = headNotes.Replace("#Version#", Application.unityVersion);
headNotes = headNotes.Replace("#DATE#", System.DateTime.Now.ToString("yyyy-MM-dd"));
File.WriteAllText(_newFile, headNotes);
}
}
第二种:
是直接更改Unity创建脚本的模板,然后再通过脚本来更改
先贴一下模板文件的位置
D:\Unity\Editor\Data\Resources\ScriptTemplates\81-C# Script-NewBehaviourScript.cs.txt
将这段注释贴在TXT文件的最上方即可
/**
*Copyright(C) 2015 by #COMPANY#
*All rights reserved.
*FileName: #SCRIPTFULLNAME#
*Author: #AUTHOR#
*Version: #VERSION#
*UnityVersion:#UNITYVERSION#
*Date: #DATE#
*Description:
*History:
*/
然后即可利用上面脚本的方式去更改两个#中间的文字
public class AddFileHead : UnityEditor.AssetModificationProcessor
{
/// <summary>
/// 此函数在asset被创建完,文件已经生成到磁盘上,但是没有生成.meta文件和import之前被调用
/// </summary>
/// <param name="_newFielMeta">newfilemeta 是由创建文件的path加上.meta组成的</param>
public static void OnWillCreateAsset(string _newFielMeta)
{
string newFielPath = _newFielMeta.Replace(".meta", "");
string fileExt = Path.GetExtension(newFielPath);
if (!fileExt.Equals(".cs"))
{
return;
}
string realPath = Application.dataPath.Replace("Assets", "") + newFielPath;
string scriptContent = File.ReadAllText(realPath);
//定义规则
scriptContent = scriptContent.Replace("#SCRIPTFULLNAME#", Path.GetFileName(newFielPath));
scriptContent = scriptContent.Replace("#COMPANY#", PlayerSettings.companyName);
scriptContent = scriptContent.Replace("#AUTHOR#", "");
scriptContent = scriptContent.Replace("#VERSION#", "");
scriptContent = scriptContent.Replace("#UNITYVERSION#", Application.unityVersion);
scriptContent = scriptContent.Replace("#DATE#", System.DateTime.Now.ToString("yyyy-MM-dd"));
File.WriteAllText(realPath, scriptContent);
}
}