添加命名空间是开发中常见的需求,所以我就自己写了一个小东西
实现思路
我的实现思路是
首先 需要一个生成脚本的帮助类,详见自动创建脚本插件
然后 我们需要知道新建脚本的类名,这个可以用编辑器脚本实现
继承AssetModificationProcessor,当Unity编辑器内的资源记性操纵的时候,会调用对应的回调函数
最后 根据获取到的类名生成新的脚本内容,覆盖原本的脚本
public class AutoAddNameSpace : UnityEditor.AssetModificationProcessor
{
//这个函数会在有新的资源创建的时候调用
private static void OnWillCreateAsset(string path)
{
path = path.Replace(".meta", "");
if (path.EndsWith(".cs"))
{
string text = "";
text += File.ReadAllText(path);
string name = GetClassName(text);
if (string.IsNullOrEmpty(name))
{
return;
}
var newText = GetNewScriptContext(name);
File.WriteAllText(path, newText);
}
AssetDatabase.Refresh();
}
//获取新的脚本内容
private static string GetNewScriptContext(string className)
{
var script = new ScriptBuildHelp();
script.WriteUsing("UnityEngine");
script.WriteEmptyLine();
script.WriteNamespace("UIFrame");
script.IndentTimes++;
script.WriteClass(className);
script.IndentTimes++;
script.WriteFun("Start");
return script.ToString();
}
//获取类名
private static string GetClassName(string text)
{
string patterm = "public class ([A-Za-z0-9_]+)\\s*:\\s*MonoBehaviour";
var match = Regex.Match(text, patterm);
if (match.Success)
{
return match.Groups[1].Value;
}
return "";
}
}
工具收录于我自己写的工具集,内部还有我写的几个小插件,我会慢慢更新,欢迎关注
工具集地址:https://github.com/BlueMonk1107/BlueToolkit
我会在我的公众号上推送新的博文,也可以帮大家解答问题
微信公众号 Andy and Unity 搜索名称或扫描二维码
希望我们能共同成长,共同进步