使用 zwcloud 的回答和 some other resources 我能够在我的脚本文件上生成一个命名空间:
第一步,导航:
Unity 的默认模板可以在您的 Unity 安装目录下找到,对于 Windows,Editor\Data\Resources\ScriptTemplates 和对于 OSX 的 /Contents/Resources/ScriptTemplates。
并打开文件81-C# Script-NewBehaviourScript.cs.txt
并进行以下更改:
namespace #NAMESPACE# {
在顶部和
}
在底部。缩进其余部分,以便空格符合需要。暂时不要保存这个。如果您愿意,您可以对模板进行其他更改,例如删除默认的 cmets、制作 Update() 和 Start() private,甚至完全删除它们。
同样,暂时不要保存此文件,否则 Unity 将在下一步中抛出错误。如果已保存,只需按 ctrl-Z 撤消然后重新保存,然后按 ctrl-Y 重新应用更改。
现在在 Unity Assets 目录中的 Editor 文件夹中创建一个新脚本,并将其命名为 AddNameSpace。将内容替换为:
using UnityEngine;
using UnityEditor;
public class AddNameSpace : UnityEditor.AssetModificationProcessor {
public static void OnWillCreateAsset(string path) {
path = path.Replace(".meta", "");
int index = path.LastIndexOf(".");
if(index < 0) return;
string file = path.Substring(index);
if(file != ".cs" && file != ".js" && file != ".boo") return;
index = Application.dataPath.LastIndexOf("Assets");
path = Application.dataPath.Substring(0, index) + path;
file = System.IO.File.ReadAllText(path);
string lastPart = path.Substring(path.IndexOf("Assets"));
string _namespace = lastPart.Substring(0, lastPart.LastIndexOf('/'));
_namespace = _namespace.Replace('/', '.');
file = file.Replace("#NAMESPACE#", _namespace);
System.IO.File.WriteAllText(path, file);
AssetDatabase.Refresh();
}
}
保存此脚本并将更改保存到81-C# Script-NewBehaviourScript.cs.txt
你就完成了!您可以通过在 Assets 内的任何一系列文件夹中创建一个新的 C# 脚本来测试它,它将生成我们创建的新命名空间定义。