Unity Editor - Custom Script Templates

Unity Editor - Custom Script Templates

Script template for Unity editor

Add your own template in the script template folder of the Unity editor. After restarting the editor, it will automatically recognize and display the available templates in Assets/Create (right-click menu in Project)
Note: After adding a custom template, you must restart the editor to take effect.
Template file location: Editor installation location\Editor\Data\Resources\ScriptTemplates
Template file location
Template file naming format description: (Take 81-Script__MonoBehaviour-NewBehaviour.cs.txt as an example)

81 Script MonoBehaviour NewBehaviour.cs
Menu location Menu name (can be separated by __, multi-level submenu) option name Default file name

Description of common keywords in templates:

#ROOTNAMESPACEBEGIN# #ROOTNAMESPACEEND# #SCRIPTNAME# #NAME#
Mark the root namespace of the script Mark the root namespace of the script File name (C# script sets the file name to the class name by default) File name (Shader sets the file name to the Shader name by default)

If you place the script template directly in the editor installation location \Editor\Data\Resources\ScriptTemplates , you will need to repeat the above operations for the newly installed editor when upgrading the editor. For this, you can directly place the script template (with the same naming rules ) is saved in the Assets/ScriptTemplates folder. After restarting the Unity editor, the editor will automatically recognize it and display it in the right-click menu; then export the Assets/ScriptTemplates folder to .unitypackage to use it in other projects.

MenuItem

First prepare the script template ScriptTemplate.cs.txt and place it in the Assets/ScriptTemplates folder.

/*
┌────────────────────────────┐
│ Description:
│ Author:
│ Remark:可在自定义的脚本模板中按自身需求添加版权信息、脚本说明等
└────────────────────────────┘
┌──────────────┐                                   
│ ClassName:#SCRIPTNAME#
└──────────────┘
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    #ROOTNAMESPACEBEGIN#
public class #SCRIPTNAME# : MonoBehaviour
{
    
    

}
#ROOTNAMESPACEEND#

Add the editor script CreateMyScript.cs in the Assets/Scripts/Editor folder

using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;

public static class CreateScript
{
    
    
    [MenuItem("Assets/Create/My Script", false, 80)]
    public static void CreatNewLua()
    {
    
    
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
        ScriptableObject.CreateInstance<CreateScriptAsset>(),
        GetSelectedPathOrFallback() + "/NewScript.cs",
        null,
       "Assets/ScriptTemplates/ScriptTemplate.cs.txt");
    }

    public static string GetSelectedPathOrFallback()
    {
    
    
        string path = "Assets";
        foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets))
        {
    
    
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
    
    
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        return path;
    }

    class CreateScriptAsset : EndNameEditAction
    {
    
    
        public override void Action(int instanceId, string pathName, string resourceFile)
        {
    
    
            UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile);
            ProjectWindowUtil.ShowCreatedAsset(o);
        }

        internal static Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
        {
    
    
            string fullPath = Path.GetFullPath(pathName);
            StreamReader streamReader = new StreamReader(resourceFile);
            string text = streamReader.ReadToEnd();
            streamReader.Close();
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
            text = Regex.Replace(text, "#SCRIPTNAME#", fileNameWithoutExtension);
            text = Regex.Replace(text, "#ROOTNAMESPACEBEGIN#", string.Empty);
            text = Regex.Replace(text, "#ROOTNAMESPACEEND#", string.Empty);
            bool encoderShouldEmitUTF8Identifier = true;
            bool throwOnInvalidBytes = false;
            UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
            bool append = false;
            StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
            streamWriter.Write(text);
            streamWriter.Close();
            AssetDatabase.ImportAsset(pathName);
            return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object));
        }
    }
}

References

https://www.xuanyusong.com/archives/3732
https://github.com/hubertgdev/unity-script-templates

Guess you like

Origin blog.csdn.net/weixin_43430402/article/details/128803195