Unity custom script template adds head comments, mother no longer has to worry about changing my computer to unity version

It’s been a long time since I wrote an article on csdn, and I also made a blog of my own. If you are interested, you can check it out.
Link: https://zeroultra.github.io/
Back to the topic, this article talks about how to customize the template

Some problems with custom templates

In fact, many articles have written custom templates and added head comments, such as this article . They are all to find untiy's own template c# txt, and then write the relevant replacement code, and replace it in the match. The problems:

  1. When the computer is changed, or the unity version is changed, the template must be found again and written
  2. Cannot add multiple templates

How to customize the template

There are two methods need to know ProjectWindowUtil.CreateAssetWithContentand OnWillCreateAssetcan look API manual
https://docs.unity3d.com/ScriptReference/AssetModificationProcessor.OnWillCreateAsset.html
https://docs.unity3d.com/462/Documentation/ScriptReference/ProjectWindowUtil.html

After knowing these two methods,
we can do it. We can create a Editorfolder in unity , and then customize a c# template. I defined two, one inherits mono and the other does not inherit mono (txt file)

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()
    {
    
    
        
    }
}

another

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

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

Insert picture description here
Then we create aScriptTemplatesGenerate.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);
        }
    }
}

The code has been commented, so I won't say more. Finally, let's take a look at the effect.
Insert picture description here
You can see that there are two more menu options, and then click Create to create a custom template.

I found an article when I was visiting the b war: https://www.bilibili.com/read/cv6097455
This is also feasible, we can completely empty the template that comes with unity and write it into the .cs text in our content If I don't do this, it will be messy when the string is spliced ​​or I write a template and put it in my own frame or a specific folder.

According to this idea, we can also customize other templates

In fact, there is another way. For reference, I think it is a little more troublesome, but it is better to learn some knowledge
https://www.xuanyusong.com/archives/3732

Guess you like

Origin blog.csdn.net/K20132014/article/details/106225474