赞
踩
内容将会持续更新,有错误的地方欢迎指正,谢谢!
拥有更好的学习体验 —— 不断努力,不断进步,不断探索 |
助力快速掌握 头部注释 自动添加 为初学者节省宝贵的学习时间,避免困惑! |
在 Unity 开发中,我们常常需要在创建新脚本时添加一些标准化的头注释,例如作者姓名、创建日期等。手动添加这些信息既麻烦又容易出错。本文将介绍在创建C# Scripts时如何自动添加脚本注释头,并提供一个完整的示例代码。
TechX 教程效果:
从零开始创建Unity自定义包Package:一步一步实现您的功能
在工程文件的Packages文件夹下创建一个文件夹作为包的根目录,文件夹的名称为com.fxb.scriptheadcomments_v1.0.0,文件夹结构如下图所示:
Editor文件夹:
放置Unity编辑器脚本。
Resources文件夹:
包含这个包用到的一些资源文件。
CHANGELOG.md日志记录文件:
文件中记录新增功能、改进和错误修复等信息。
package.json包清单文件:
包含包的元信息,如名称、版本、依赖项等。
打开package.json文件,填入以下包清单信息。
{
"name": "com.fxb.scriptheadcomments",
"displayName": "ScriptHeadComments",
"version": "1.0.0",
"unity": "2021.3",
"description": "Displays the script header information",
"keywords": [
"scripthead",
"script",
"head",
"comments"
],
"unityRelease": "38f1"
}
等待Unity编译完成,可以查看到该包已经导入到工程中。
在Editor文件夹中添加一个程序集,通过Create/Assembly Definition创建com.fxb.ScriptHeadComments.Editor程序集
创建完成后,设置Platforms平台为Edito。
在Unity中新建C# Script时,Unity使用的是编辑器中默认的C#脚本模板。我们可以直接在该模板文件中添加自定义注释。
我安装的Unity版本是Unity 2021.3.38f1,脚本模板文件在Unity 2021.3.38f1\Editor\Data\Resources\ScriptTemplates文件夹下
其中81-C# Script-NewBehaviourScript.cs.txt为C# 脚本模板。
使用记事本打开81-C# Script-NewBehaviourScript.cs.txt文件,并在头部添加注释信息
/************************************************************************* * Copyright © 2023-2030 Administrator. All rights reserved. *------------------------------------------------------------------------ * 公司:DefaultCompany * 项目:Unity * 文件:NewBehaviourScript.cs * 作者:Administrator * 日期:2024/7/4 20:11:28 * 功能:Nothing *************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; #ROOTNAMESPACEBEGIN# public class #SCRIPTNAME# : MonoBehaviour { // Start is called before the first frame update void Start() { #NOTRIM# } // Update is called once per frame void Update() { #NOTRIM# } } #ROOTNAMESPACEEND#
在Unity中新建一个脚本,可以查看到我们添加的脚本已经有了头部注释信息。
从上面的操作来看,如果直接在Unity的默认C#脚本模板中添加注释头,那么在新建脚本的时候,头部的注释信息是无法改变的,这不是我们想要的,我们需要的应该是在新建脚本的时候头部注释信息应该是能动态变化的。
这里使用特殊占位符进行占位
/************************************************************************* * Copyright © 2023-2030 #USERNAME#. All rights reserved. *------------------------------------------------------------------------ * 公司:#COMPANYNAME# * 项目:#PROJECTNAME# * 文件:#FILEEXTENSION# * 作者:#AUTHORNAME# * 日期:#CREATETIME# * 功能:Nothing *************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace #ASSEMBLYNAME# { #ROOTNAMESPACEBEGIN# public class #SCRIPTNAME# : MonoBehaviour { // Start is called before the first frame update void Start() { #NOTRIM# } // Update is called once per frame void Update() { #NOTRIM# } } #ROOTNAMESPACEEND# }
这里不在直接在Unity默认C# 脚本模板81-C# Script-NewBehaviourScript.cs.txt中进行添加注释头
而是在包路径的Resources中添加一个81-C# Script-NewBehaviourScript.cs.txt文件,讲下面内容粘贴到该模板文件中。
将要动态写入脚本模板的信息保存到ScriptableObj资源中,在创建脚本的时候就可以读取ScriptableObject中的变量并写入到脚本模板中。
在Editor文件夹中新建脚本ScriptHeadComments
using System; using UnityEngine; namespace ScriptHeadComments.Editor { [CreateAssetMenu(fileName = "ScriptHeadComments", menuName = "ScriptableObjects/ScriptHeadComments", order = 1)] public class ScriptHeadComments : ScriptableObject { [SerializeField] [HideInInspector] private bool isInitialized; public string authorName; public string assembleName; private void OnEnable() { if (!isInitialized) { authorName = Environment.UserName; assembleName = "NAMESPACE"; isInitialized = true; } } } }
在Resources文件家中通过Create/ScriptableObjects/ScriptHeadComments创建一个ScriptHeadComments资源。
AssetModificationProcessor 类是 Unity 编辑器中用于处理资产修改事件的一个类。它提供了一系列静态方法,这些方法在 Unity 的资产(例如脚本、预制件、材质等)被创建、移动或删除时被调用。通过继承 AssetModificationProcessor 类,可以在这些资产修改事件发生时执行自定义的逻辑。
当脚本被创建时,OnWillCreateAsset 会被调用,我们在这里处理注释头信息。
在Editor文件夹中新建脚本ScriptsProcessor
using System; using System.IO; using System.Reflection; using UnityEditor; using UnityEngine; using System.Text.RegularExpressions; namespace ScriptHeadComments.Editor { public class ScriptsProcessor : UnityEditor.AssetModificationProcessor { private const double NewFileThresholdInSeconds = 1.0; // 1秒的时间阈值 /// <summary> /// 当在Unity中新建脚本时会调用 /// 当从外部导入新脚本时会调用 /// </summary> /// <param name="path"></param> private static void OnWillCreateAsset(string path) { ScriptHeadComments scriptHead = Resources.Load<ScriptHeadComments>("ScriptHeadComments"); if (scriptHead == null) return; path = path.Replace(".meta", ""); if (path.EndsWith(".cs")) { //添加判断脚本是否新建的 if (!CheckScriptNewBuild(path)) return; try { string scriptTemplate = File.ReadAllText(SourceScriptTemplatePath); scriptTemplate = scriptTemplate.Replace("#USERNAME#", Environment.UserName); scriptTemplate = scriptTemplate.Replace("#COMPANYNAME#", PlayerSettings.companyName); scriptTemplate = scriptTemplate.Replace("#PROJECTNAME#", PlayerSettings.productName); scriptTemplate = scriptTemplate.Replace("#FILEEXTENSION#", Path.GetFileName(path)); scriptTemplate = scriptTemplate.Replace("#AUTHORNAME#", scriptHead.authorName); scriptTemplate = scriptTemplate.Replace("#CREATETIME#", string.Concat(DateTime.Now.ToString("d"), " ", DateTime.Now.Hour, ":", DateTime.Now.Minute, ":", DateTime.Now.Second)); scriptTemplate = scriptTemplate.Replace("#ASSEMBLYNAME#", scriptHead.assembleName); scriptTemplate = Regex.Replace(scriptTemplate, @"\s*#ROOTNAMESPACEBEGIN#", string.Empty); scriptTemplate = scriptTemplate.Replace("#SCRIPTNAME#", Path.GetFileNameWithoutExtension(path)); scriptTemplate = scriptTemplate.Replace("#NOTRIM#", ""); scriptTemplate = Regex.Replace(scriptTemplate, @"\s*#ROOTNAMESPACEEND#", string.Empty); File.WriteAllText(path, scriptTemplate); } catch (Exception e) { Debug.LogException(e); } } } /// <summary> /// 检查脚本是否新建的 /// </summary> /// <param name="path"></param> private static bool CheckScriptNewBuild(string path) { string fullPath = Path.GetFullPath(path); DateTime lastWriteTime = File.GetLastWriteTime(fullPath); // 如果文件在创建后1秒内被修改,则认为是新建脚本,否则是导入的脚本 if (lastWriteTime.AddSeconds(NewFileThresholdInSeconds) >= DateTime.Now) { return true; } return false; } /// <summary> /// 源脚本模板 /// </summary> static string SourceScriptTemplatePath { get { var assembly = Assembly.GetExecutingAssembly(); var pInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(assembly); if (pInfo == null) return null; var customTemplatePath = Path.GetFullPath(pInfo.assetPath); customTemplatePath = Path.Combine(customTemplatePath, "Resources/81-C# Script-NewBehaviourScript.cs.txt"); customTemplatePath = customTemplatePath.Replace('\\', '/'); return customTemplatePath; } } } }
读取模板文件内容,并替换其中的占位符,将修改后的模板内容写入新创建的脚本文件中。
工程地址:
https://gitcode.com/CTLittleNewbie/com.fxb.scriptheadcomments_v1.0.0
每一次跌倒都是一次成长 每一次努力都是一次进步 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。