自动添加命名空间

添加命名空间是开发中常见的需求,所以我就自己写了一个小东西

实现思路

我的实现思路是

首先 需要一个生成脚本的帮助类,详见自动创建脚本插件

然后 我们需要知道新建脚本的类名,这个可以用编辑器脚本实现
继承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 搜索名称或扫描二维码
在这里插入图片描述
希望我们能共同成长,共同进步

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值