Unity 自定義腳本模板 添加頭部註釋 媽媽再也不用擔心我換電腦 換unity版本了

好久沒在csdn 上面寫文章了,我也搗鼓了一個自己的 blog 有興趣可以來看看
鏈接:https://zeroultra.github.io/
回到正題,本文講如何自定義模板

自定義模板的一些問題

其實有很多文章都寫了自定義模板,添加頭部註釋,例如這篇文章. 都是要找到untiy 自己的模板c# txt,然後寫入相關的替代碼,在匹配更換,其中的問題:

  1. 當換電腦,或者unity換了一個unity版本之後,又得重新找到模板,寫入
  2. 無法添加多個模板

如何自定義模板

這裏有兩個方法 需要知道 ProjectWindowUtil.CreateAssetWithContentOnWillCreateAsset,可以查查API 手冊
https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.OnWillCreateAsset.html
https://docs.unity3d.com/462/Documentation/ScriptReference/ProjectWindowUtil.html

知道這兩個方法之後就好做了
我們可以在unity中創建一個Editor文件夾,然後自定義一個 c#模板,我定義了兩個,一個繼承mono,一個不繼承mono(txt文件)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// --(*^__^*) --
/// ____AUTHOR:    #AUTHOR#
/// ____DATE:      #DATE#
/// ____DESC:      #DESC#
/// ____VERSION:	   #VERSION#
/// ____UNITYVERSION:  #UNITYVERSION#
/// --(=^ω^=) --
/// </summary>

public class #SCRIPTNAME# : MonoBehaviour
{
    private void Start()
    {
        
    }
}

另一個

using System.Collections;
/// <summary>
/// --(*^__^*) --
/// ____AUTHOR:    #AUTHOR#
/// ____DATE:      #DATE#
/// ____DESC:      #DESC#
/// ____VERSION:	   #VERSION#
/// --(=^ω^=) --
/// </summary>

public class #SCRIPTNAME# 
{
   public  #SCRIPTNAME#()
   {
   
   }
}

在這裏插入圖片描述
然後 我們創建一個ScriptTemplatesGenerate.cs

/* 自定義 C# 模板創建
 * 在修改unity自定義的模板之後,換個版本,換個電腦又是原樣了
 * 所以得自己定義一個
 *幫助鏈接
 *("https://blog.csdn.net/mobilebbki399/article/deta
 */


using UnityEngine;
using UnityEditor;
using System;
using System.IO;

public class ScriptTemplatesGenerate
{
    //模板文件位置
    static string tempCshapeMonoBehaviourPath = Application.dataPath + "//Editor/NewBehaviourScriptTemplates.txt";
    static string tempCshapePath = Application.dataPath + "/Editor/NewScriptTemplates.txt";

    [MenuItem("Assets/Create/My C# MonoBehaviour Script", false, 80)]
    static void CreateMyMonoBehaviourCShapeScrtip()
    {

        ScriptGenerate(true);
    }
    [MenuItem("Assets/Create/My C#  Script", false, 80)]
    static void CreateMyCShapeScrtip()
    {

        ScriptGenerate(false);
 
    }

    private static void ScriptGenerate(bool isMonoBehaviour)
    {
        try
        {
            if (isMonoBehaviour)
                ProjectWindowUtil.CreateAssetWithContent("NewBehaviourScript.cs", File.ReadAllText(tempCshapeMonoBehaviourPath), EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D);
            else
                ProjectWindowUtil.CreateAssetWithContent("NewScript.cs", File.ReadAllText(tempCshapePath), EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D);

        }
        catch (Exception ex)
        {
            Debug.LogError("模板文件路徑錯誤!!! " + ex.Message);
        }
    }

    /// <summary>
    /// 給腳本添加標題頭
    /// </summary>
    class AddFileHeadComment : UnityEditor.AssetModificationProcessor
    {
        /// <summary>
        /// 此函數在asset被創建,文件已經生成到磁盤上,生成了.meta文件沒有正式創建完成之間調用(我覺得) 和import之前被調用
        /// </summary>
        /// <param name="newFileMeta">newfilemeta 是由創建文件的path加上.meta組成的</param>
        public static void OnWillCreateAsset(string newFileMeta)
        {

            //把meta去掉
            string newFilePath = newFileMeta.Replace(".meta", "");
            //得到擴展名
            string fileExt = Path.GetExtension(newFilePath);

            if (fileExt != ".cs") return;

            string realPath = Application.dataPath.Replace("Assets", "") + newFilePath;
            string scriptContent = File.ReadAllText(realPath);

            //這裏實現自定義的一些規則
            scriptContent = scriptContent.Replace("#SCRIPTNAME#", Path.GetFileName(Path.GetFileNameWithoutExtension(newFilePath)));
            //scriptContent = scriptContent.Replace("#COMPANY#", PlayerSettings.companyName);
            scriptContent = scriptContent.Replace("#AUTHOR#", "海賊王");
            scriptContent = scriptContent.Replace("#DESC#", "文件描述");
            scriptContent = scriptContent.Replace("#VERSION#", "1.0");
            scriptContent = scriptContent.Replace("#UNITYVERSION#", Application.unityVersion);
            scriptContent = scriptContent.Replace("#DATE#", DateTime.Now.ToString("yyyy-MM-dd"));

            File.WriteAllText(realPath, scriptContent);
            //一定要加這句話 不然 在創建之後點擊腳本預覽發現還是原來模板效果
            //一開始就是沒加這句話 所以有bug 這就導致了第二個方法產生
            AssetDatabase.ImportAsset(newFilePath);
        }
    }
}

代碼已經寫了註釋 就不再多說,最後來看看效果
在這裏插入圖片描述
可以看到多出了兩個菜單選項,然後點擊創建即爲自定義模板.

我在逛b戰的時候發現一篇文章: https://www.bilibili.com/read/cv6097455
這個也可行,我們完全可以把unity自帶的模板清空然後在自己的內容寫入到.cs文本中,我不這麼做就是字符串拼接到時候會很亂 還是自己寫個模板放着,放到 自己框架 或者特定的文件夾中即可.

根據這個想法 我們也可以自定義其他模板

其實還有一種方法 ,參考一下,我是覺得稍微麻煩些,不過學點知識也好
https://www.xuanyusong.com/archives/3732

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章