自动将命名空间添加到 Unity C# 脚本

Tom*_*das 2 c# unity-game-engine unity-editor

我熟悉为 Unity 游戏引擎更改脚本模板的能力。但是,它非常有限,只允许一个关键字:#SCRIPTNAME#

随着项目变得越来越复杂,命名空间变得至关重要。并且无法通过Create --> C# Script.

有谁知道任何解决方案?


PS 我知道您可以使用 Visual Studio 创建文件,根据位置自动获取命名空间。但是,它们包含不必要的部分,例如Assets.Scripts...

Tom*_*das 5

在网上做一些研究,我发现你可以AssetModificationProcessorpublic static void OnWillCreateAsset(string path)方法来创造。在此方法中,您可以读取创建的脚本文件并使用string.Replace(或其他方法)替换内容。

深入研究这一点,我提供了有用的编辑器脚本,它#NAMESPACE#根据项目中的脚本位置更改关键字(全部使用我当前的项目结构制作,因此您可能需要在脚本正常工作之前对其进行调整)。

如果链接断开,这里是编辑器脚本:

using System.IO;
using UnityEditor;
using UnityEngine;

namespace MyGame.Editor.Assets
{
    public sealed class ScriptAssetKeywordsReplacer : UnityEditor.AssetModificationProcessor
    {
        /// <summary>
        ///  This gets called for every .meta file created by the Editor.
        /// </summary>
        public static void OnWillCreateAsset(string path)
        {
            path = path.Replace(".meta", string.Empty);

            if (!path.EndsWith(".cs"))
            {
                return;
            }

            var systemPath = path.Insert(0, Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("Assets")));

            ReplaceScriptKeywords(systemPath, path);

            AssetDatabase.Refresh();
        }


        private static void ReplaceScriptKeywords(string systemPath, string projectPath)
        {
            projectPath = projectPath.Substring(projectPath.IndexOf("/SCRIPTS/") + "/SCRIPTS/".Length);
            projectPath = projectPath.Substring(0, projectPath.LastIndexOf("/"));
            projectPath = projectPath.Replace("/Scripts/", "/").Replace('/', '.');

            var rootNamespace = string.IsNullOrWhiteSpace(EditorSettings.projectGenerationRootNamespace) ?
                string.Empty :
                $"{EditorSettings.projectGenerationRootNamespace}.";

            var fullNamespace = $"{rootNamespace}{projectPath}";

            var fileData = File.ReadAllText(systemPath);

            fileData = fileData.Replace("#NAMESPACE#", fullNamespace);

            File.WriteAllText(systemPath, fileData);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在名为 的文件夹下添加此脚本后Editor,您需要更改位于 .c# 的 c# 脚本模板%EditorPath%/Data/Resources/ScriptTemplates/81-C# Script-NewBehaviourScript.cs.txt。打开此文件并添加包装类

namespace #NAMESPACE#
{
    // All the class template can stay the same
}
Run Code Online (Sandbox Code Playgroud)