你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

编辑器扩展

2021/12/13 17:34:03

问题:编写代码时会有很多UI的查找、事件监听等经常重复编写的代码。因此通过编辑器去自动初始化生成代码。

目的:开发效率的提高

首先,根据需求,准备预制体……废话不多开始心路历程:

  1. 确定生成脚本Demo:
    public static string UIClass =
            @"using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class #类名# : MonoBehaviour
    {
        #预设成员变量#
    
        void Start()
        {
           #查找#
           #事件#
        }
        #事件方法#
    }";
  2. 根据选中准备好的预制体,准备并替换其中的‘#*#’内容:
        string 类名;
        string 成员变量;
        string 查找成员;
        string 事件;
        string 事件方法;
        public static void GetObjsDefintion(Transform tf)
        {
            类名 = tf.name+"Script";
            if (tf != null)
            {
                for (int i = 0; i < tf.childCount; i++)
                {
                    //根据命名格式筛选出所需要记录的成员
                    if (tf.GetChild(i).name.StartsWith("R_"))
                    {
                        if (tf.GetChild(i).name.EndsWith("_Text"))
                        {                    
                            //根据命名格式去逐个递归查找路径来查找每一个成员变量
                            成员变量 += "private Text " + name + ";\n     ";
                            查找成员 += name + " = transform.Find(\"" + "递归查找路径" + "\").GetComponent<Text>(); \n     ";
                        }
                        else if (tf.GetChild(i).name.EndsWith("_Button"))
                        {
                            //需要事件监听的Button等添加事件以及事件方法
                            事件 += name + ".onClick.AddListener("+name+"Listener);";
                            事件方法 += "private void "+name+"Listener(){}";
                        }else{
                            //别的需要的内容,此处省略一万行代码
                        }
                    }
    
                    if (tf.GetChild(i).childCount > 0 )
                    {
                        //递归遍历所有子物体
                        GetObjsDefintion(tf.GetChild(i));
                    }
                }
            }
        }
        
        string classStr = PrefabToScriptTemplate.UIViewClass;
        classStr = classStr.Replace("#类名#", 类名);
        classStr = classStr.Replace("#预设成员变量#", 成员变量);
        classStr = classStr.Replace("#查找#", 查找成员);
        classStr = classStr.Replace("#事件#", 事件);
        classStr = classStr.Replace("#事件方法#", 事件方法);
  3. 确定生成脚本的路径、并生成:

            string scriptPath = Application.dataPath + "/Scripts/" + 类名 + ".cs";
            FileStream file = new FileStream(scriptPath, FileMode.CreateNew);
            StreamWriter filew = new StreamWriter(file, System.Text.Encoding.UTF8);
            filew.Write(classStr);
            filew.Flush();
            filew.Close();
            file.Close();



    链接: https://pan.baidu.com/s/1DRJyQhBNrwjoHZnpS51Wyg 提取码: q188