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

Automatically add namespace to Unity C# script

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

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

使用适当的命名空间生成脚本

有人知道解决这个问题的方法吗?


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

通过在线研究,我发现您可以使用 public static void OnWillCreateAsset(string path) 方法创建 AssetModificationProcessor。在此方法中,您可以读取创建的脚本文件并使用 string.Replace(或其他方法)替换内容。

深入了解这一点,我带来了有用的 Editor script,它根据项目中的脚本位置更改 #NAMESPACE# 关键字(所有这些都是使用我当前的项目结构制作的,因此您可能需要在脚本正常工作之前调整脚本)。

以防 link 损坏,这里是编辑器脚本:

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);
        }
    }
}

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

namespace #NAMESPACE#
{
    // All the class template can stay the same
}