unity生成代码模板

    xiaoxiao2021-03-26  27

            一千个莎士比亚就会有一千个哈姆雷特,每个技术人员的代码风格和命名规范都不尽相同,而一套规范清晰统一的代码对我们日后项目的维护有着重要的意义,而且模板生成工具会大大节省我们重复工作量。

           unity中我们可以在Project面板右键或通过Assets菜单创建脚本或是shader,unity为我们提供了C#,javascript脚本以及四个shader代码的模板,当创建这些脚本时实际上是复制这些模板并改变其类名或是shader名,我们可以在Unity的安装目录下找到这些代码模板文件:D:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates。

           我们在unity中右键创建出来的代码通过对UnityEditor.dll的反编译,可以看到主要是通过ProjectWindowUtil.StartNameEditingIfProjectWindowExists这个方法执行的

    using UnityEngine; using UnityEditor; using System.Collections; using UnityEditor.ProjectWindowCallback; using System.IO; public class CreateScriptAction : EndNameEditAction { public override void Action(int instanceId, string pathName, string resourceFile) { //创建资源 Object obj = ProjectWindowUtil.CreateAssetFormTemplate(pathName, resourceFile); //高亮显示该资源 ProjectWindowUtil.ShowCreatedAsset(obj); } }        接下来我们看下CreateAssetFormTemplate这个方法

    internal static Object CreateAssetFormTemplate(string pathName, string resourceFile) { //获取要创建资源的绝对路径 string fullName = Path.GetFullPath(pathName); //读取本地模版文件 StreamReader reader = new StreamReader(resourceFile); string content = reader.ReadToEnd(); reader.Close(); System.Text.UTF8Encoding utf8withoutBom = new System.Text.UTF8Encoding(false); //获取资源的文件名 string fileName = Path.GetFileNameWithoutExtension(pathName); //替换默认的文件名 content = content.Replace("#NAME", fileName); //写入新文件 StreamWriter writer = new StreamWriter(fullName, false, utf8withoutBom); writer.Write(content); writer.Close(); //刷新本地资源 AssetDatabase.ImportAsset(pathName); AssetDatabase.Refresh(); return AssetDatabase.LoadAssetAtPath(pathName, typeof(Object)); }       主要是用了StreamReader和StreamWriter将模板文件进行更改和拷贝

           好了,接下来我们便可以自己写一些代码模板,用反射的方式来让Unity帮我们处理这些模板并创建代码

    [MenuItem("Assets/Create/Lua/生成LuaManager(继承Singleton)", false, 1003)] public static void CreateLuaManagerFile() { string path = GetSelectedPath(); if (string.IsNullOrEmpty(path)) { return; } ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<CreateScriptAction>(), path + "/NewLua.lua", null, "Assets/Editor/ScriptTool/LuaManager.lua.txt"); } private static string GetSelectedPath() { //默认路径为Assets string selectedPath = "Assets"; //获取选中的资源 Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.Assets); if (selection.Length != 1) return ""; //遍历选中的资源以返回路径 foreach (Object obj in selection) { selectedPath = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(selectedPath) && File.Exists(selectedPath)) { selectedPath = Path.GetDirectoryName(selectedPath); break; } } return selectedPath; }

    转载请注明原文地址: https://ju.6miu.com/read-664293.html

    最新回复(0)