c# - 自动将命名空间添加到 Unity C# 脚本
问题描述
我熟悉更改 Unity 游戏引擎的脚本模板的能力。但是,它非常有限,只允许一个关键字:#SCRIPTNAME#
.
随着项目变得越来越复杂,命名空间成为至关重要的部分。并且没有办法通过Create --> C# Script
.
有谁知道任何解决方案?
PS 我知道您可以使用 Visual Studio 创建文件,这些文件会根据位置自动获取命名空间。但是,它们包含不必要的部分,例如Assets.Scripts
...
解决方案
在网上做一些研究,我发现你可以AssetModificationProcessor
用public 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);
}
}
}
在名为 的文件夹下添加此脚本后Editor
,您需要更改位于的 c# 脚本模板%EditorPath%/Data/Resources/ScriptTemplates/81-C# Script-NewBehaviourScript.cs.txt
。打开此文件并添加包装类
namespace #NAMESPACE#
{
// All the class template can stay the same
}
推荐阅读
- openssl - 加载 OpenSSL 引擎时 SO_PATH 和 MODULE_PATH 有什么区别?
- android - 无法解析片段中的 findViewById
- python - 如何更新嵌套字典
- android - 检查设备是否有服务中的缺口
- php - Android 测试 - 模拟多个用户
- aurelia - aurelia 中的子路由,要实现的附加 configureRoutes 或视口
- postgresql - Amazon RDS IAM PAM 身份验证失败
- javascript - 使用 javascript / jquery 删除“/”字符的最后一次迭代之前的任何文本
- swift - 如何用多个参数替换多个 StringProtocol
- php - 从字符串中查找特定文本并将其与数据库匹配