unity 导出ui初始化代码

项目ui代码初始化部分 一般都可以自动生成。

原因:主要是手动填写ui node节点的路径,费时间。

实现结果:借助于插件 QHierarchy ,添加点选控制,只导出自己想要的节点。如下图红框内打钩的component是要导出代码。

步骤:1.点选 2.选预制件 3.点击导出 4.结果(具体代码文件不贴出来,而且每个项目可能ui代码规则不同)

实现方式:

主要是两部分代码:1.编辑器下 QHierarchy 代码插入  2.导出lua文件的代码

1.插入到QHierarchy

仿照QLockComponent.cs的流程,新加QToLuaUIComponent.cs类。此类是每个GameObject节点的显示和操作

  1 using System;
  2 using System.Collections.Generic;
  3 using UnityEngine;
  4 using UnityEditor;
  5 using qtools.qhierarchy.pcomponent.pbase;
  6 using qtools.qhierarchy.phierarchy;
  7 using qtools.qhierarchy.phelper;
  8 using qtools.qhierarchy.pdata;
  9 /// <summary>
 10 /// 2020年1月10日 by chenfei
 11 /// 实现自动导出初始ui代码
 12 /// </summary>
 13 namespace qtools.qhierarchy.pcomponent
 14 {
 15     public class QToLuaUIComponent : QBaseComponent
 16     {
 17         // PRIVATE
 18         private Color activeColor;
 19         private Color inactiveColor;
 20         private Color specialColor;
 21         private Texture2D chooseButtonTexture;
 22         private int targetVisibilityState = -1;
 23 
 24         // CONSTRUCTOR
 25         public QToLuaUIComponent()
 26         {
 27             rect.width = 14;
 28 
 29             chooseButtonTexture = QResources.getInstance().getTexture(QTexture.QCheckBoxChecked);
 30 
 31             QSettings.getInstance().addEventListener(QSetting.ToLuaUI, settingsChanged);
 32             QSettings.getInstance().addEventListener(QSetting.ToLuaUI, settingsChanged);
 33             QSettings.getInstance().addEventListener(QSetting.AdditionalActiveColor         , settingsChanged);
 34             QSettings.getInstance().addEventListener(QSetting.AdditionalInactiveColor       , settingsChanged);
 35             QSettings.getInstance().addEventListener(QSetting.AdditionalSpecialColor        , settingsChanged);
 36             settingsChanged();
 37         }
 38 
 39         private void settingsChanged()
 40         {
 41             enabled                     = QSettings.getInstance().get<bool>(QSetting.ToLuaUI);
 42             showComponentDuringPlayMode = QSettings.getInstance().get<bool>(QSetting.ToLuaUI);
 43             activeColor                 = QSettings.getInstance().getColor(QSetting.AdditionalActiveColor);
 44             inactiveColor               = QSettings.getInstance().getColor(QSetting.AdditionalInactiveColor);
 45             specialColor                = QSettings.getInstance().getColor(QSetting.AdditionalSpecialColor);
 46         }
 47 
 48         // DRAW
 49         public override QLayoutStatus layout(GameObject gameObject, QObjectList objectList, Rect selectionRect, ref Rect curRect, float maxWidth)
 50         {
 51             if (maxWidth < 18)
 52             {
 53                 return QLayoutStatus.Failed;
 54             }
 55             else
 56             {
 57                 curRect.x -= 18;
 58                 rect.x = curRect.x;
 59                 rect.y = curRect.y;
 60                 return QLayoutStatus.Success;
 61             }
 62         }
 63 
 64         public override void disabledHandler(GameObject gameObject, QObjectList objectList)
 65         {
 66           //  Debug.Log("disabledHandler");
 67             if (objectList != null)
 68             {
 69                 if (gameObject.activeSelf && objectList.editModeVisibileObjects.Contains(gameObject))
 70                 {
 71                     objectList.editModeVisibileObjects.Remove(gameObject);
 72                     gameObject.SetActive(false);
 73                     EditorUtility.SetDirty(gameObject);
 74                 }
 75                 else if (!gameObject.activeSelf && objectList.editModeInvisibleObjects.Contains(gameObject))
 76                 {
 77                     objectList.editModeInvisibleObjects.Remove(gameObject);
 78                     gameObject.SetActive(true);
 79                     EditorUtility.SetDirty(gameObject);
 80                 }
 81             }
 82         }
 83 
 84         public override void draw(GameObject gameObject, QObjectList objectList, Rect selectionRect)
 85         {
 86             bool isChoose = isGameObjectChoose(gameObject, objectList);
 87 
 88             //if (isChoose == true )
 89             //{
 90             //    EditorUtility.SetDirty(gameObject);
 91             //}
 92             //else if (isChoose == false)
 93             //{
 94             //    EditorUtility.SetDirty(gameObject);
 95             //}
 96 
 97             QColorUtils.setColor(isChoose ? activeColor : inactiveColor);
 98             GUI.DrawTexture(rect, chooseButtonTexture);
 99             QColorUtils.clearColor();
100          
101         }
102 
103         public override void eventHandler(GameObject gameObject, QObjectList objectList, Event currentEvent)
104         {
105          //   Debug.Log("==eventHandler");
106             if (currentEvent.isMouse && currentEvent.button == 0 && rect.Contains(currentEvent.mousePosition))
107             {
108                 bool isChoose = isGameObjectChoose(gameObject, objectList);
109                 if (currentEvent.type == EventType.MouseDown)
110                 {
111                     targetVisibilityState = ((!gameObject.activeSelf) == true ? 1 : 0);
112                 }
113                 else if (currentEvent.type == EventType.MouseDrag && targetVisibilityState != -1)
114                 {
115                     if (targetVisibilityState == (gameObject.activeSelf == true ? 1 : 0)) return;
116                 } 
117                 else
118                 {
119                     targetVisibilityState = -1;
120                     return;
121                 }
122                                                             
123                 bool showWarning = QSettings.getInstance().get<bool>(QSetting.AdditionalShowModifierWarning);
124                 
125                 List<GameObject> targetGameObjects = new List<GameObject>();
126                 if (currentEvent.shift)
127                 {
128                     if (!showWarning || EditorUtility.DisplayDialog("Change visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the visibility of this GameObject and all its children? (You can disable this warning in the settings)", "Yes", "Cancel"))
129                     {
130                         getGameObjectListRecursive(gameObject, ref targetGameObjects);           
131                     }
132                 }
133                 else if (currentEvent.alt) 
134                 {
135                     if (gameObject.transform.parent != null)
136                     {
137                         if (!showWarning || EditorUtility.DisplayDialog("Change visibility", "Are you sure you want to turn " + (gameObject.activeSelf ? "off" : "on") + " the visibility this GameObject and its siblings? (You can disable this warning in the settings)", "Yes", "Cancel"))
138                         {
139                             getGameObjectListRecursive(gameObject.transform.parent.gameObject, ref targetGameObjects, 1);
140                             targetGameObjects.Remove(gameObject.transform.parent.gameObject);
141                         }
142                     }
143                     else
144                     {
145                         Debug.Log("This action for root objects is supported for Unity3d 5.3.3 and above");
146                         return;
147                     }
148                 }
149                 else 
150                 {
151                     if (Selection.Contains(gameObject))
152                     {
153                         targetGameObjects.AddRange(Selection.gameObjects);
154                     }
155                     else
156                     {
157                         getGameObjectListRecursive(gameObject, ref targetGameObjects, 0);
158                     };
159                 }
160 
161                 setChoose(targetGameObjects, objectList, !isChoose);
162                // setVisibility(targetGameObjects, objectList, !gameObject.activeSelf, currentEvent.control || currentEvent.command);
163                 currentEvent.Use();  
164             } 
165         }
166 
167 
168         private bool isGameObjectChoose(GameObject gameObject, QObjectList objectList)
169         {
170             return objectList == null ? false : objectList.chooseObjects.Contains(gameObject);
171         }
172         private void setChoose(List<GameObject> gameObjects, QObjectList objectList, bool targetLock)
173         {
174           //  Debug.Log("==setVisibility");
175 
176             if (gameObjects.Count == 0) return;
177 
178             if (objectList == null) objectList = QObjectListManager.getInstance().getObjectList(gameObjects[0], true);
179              Undo.RecordObject(objectList, targetLock ? "Choose" : "UnChoose");
180 
181             for (int i = gameObjects.Count - 1; i >= 0; i--)
182             {
183                 GameObject curGameObject = gameObjects[i];
184                 Undo.RecordObject(curGameObject, targetLock ? "Choose" : "UnChoose");
185 
186                 if (targetLock)
187                 {
188                 
189                     if (!objectList.chooseObjects.Contains(curGameObject))
190                         objectList.chooseObjects.Add(curGameObject);
191                 }
192                 else
193                 {
194                 
195                     objectList.chooseObjects.Remove(curGameObject);
196                 }
197 
198                 EditorUtility.SetDirty(curGameObject);
199             }
200         }
201 
202 
203     }
204 }
View Code

QObjectList内加一行 

public GameObject selectPrefab = null; 用来获取预制件

QObjectListInspector内添加,用于Inspector界面的显示交互:

1             EditorGUILayout.HelpBox("export ui script", MessageType.Info, true);
2             if (GUI.Button(EditorGUILayout.GetControlRect(GUILayout.ExpandWidth(true), GUILayout.Height(20)), "ExportLuaUIScript"))
3             {
4                 foreach (QObjectList objectList in QObjectList.instances)
5                 {
6                     GameObject prefabObj = objectList.selectPrefab;
7                     QExportUIScript.BeginExport(prefabObj);
8                 }
9             }
View Code

QHierarchySettingsWindow.cs内控制 setting面板 是否开启新加的功能:

1      // -- toLuaUI--
2                 drawSeparator();
3                 drawToLuaUISetting();
4                 // -----------
View Code

QSettings内添加         ToLuaUI = 100,      public const string DEFAULT_ORDER = "0;1;2;3;4;5;6;7;8;9;10;11;12;13";  

还有其他的零碎,不想写了。

2.导出lua文件的代码

新建QExportUIScript.cs类:实现初始化 ui prefab的功能和针对 button组件生成 按钮相应接口

  1 using UnityEngine;
  2 using System;
  3 using System.Collections;
  4 using System.Collections.Generic;
  5 using System.IO;
  6 using UnityEngine.UI;
  7 #if UNITY_EDITOR
  8 using UnityEditor;
  9 #endif
 10 
 11 /// <summary>
 12 /// 2020年1月10日 by chenfei
 13 /// 实现自动导出初始ui代码
 14 /// </summary>
 15 
 16 namespace qtools.qhierarchy
 17 {
 18     public class QExportUIScript
 19     {
 20         enum CompontType
 21         {
 22             Panel = 1,
 23             Label = 2,
 24             Image = 3,
 25             Button = 4,
 26             Input = 5,
 27             Toggle = 6,
 28             Ain = 7,
 29             Slider = 8,
 30             RawImage = 9,
 31             Dropdown = 10,
 32         }
 33 
      // 下面的xx代表 代码内映射的string 34 static Dictionary<CompontType, string> exportPrefixDict = new Dictionary<CompontType, string> 35 { 36 { CompontType.Slider, "XX"}, 37 { CompontType.Ain, "xx"}, 38 { CompontType.Toggle, "xx"}, 39 { CompontType.Input, "xx"}, 40 { CompontType.Button, "xx"}, 41 { CompontType.Image, "xx"}, 42 { CompontType.Label, "xx"}, 43 { CompontType.Panel, "xx"}, 44 { CompontType.RawImage, "XX"}, 45 { CompontType.Dropdown, "xx"}, 46 }; 47 48 49 static public void BeginExport(GameObject selectPrefab) 50 { 51 if (selectPrefab == null) 52 { 53 Debug.LogError("prefab is null !!!"); 54 return; 55 } 56 List<GameObject> allChildList = new List<GameObject>(); 57 getGameObjectListRecursive(selectPrefab, ref allChildList); 58 59 List<GameObject> resultList = new List<GameObject>(); 60 foreach (QObjectList objectList in QObjectList.instances) 61 { 62 if (selectPrefab == objectList.selectPrefab) 63 { 64 List<GameObject> choosObjList = objectList.chooseObjects; 65 foreach (GameObject chooseObj in choosObjList) 66 { 67 if (allChildList.Contains(chooseObj)) 68 { 69 resultList.Add(chooseObj); 70 } 71 } 72 } 73 } 74 if (resultList.Count == 0) 75 { 76 Debug.LogError("no choose gameobj in this prefab!!!"); 77 return; 78 } 79 80 List<ObjInfo> tempShowInfoList = new List<ObjInfo>(); 81 foreach (GameObject resultObject in resultList) 82 { 83 tempShowInfoList.Add(new ObjInfo(resultObject.name, GetRelativePath(resultObject, selectPrefab), GetComType(resultObject))); 84 } 85 //--test: 86 //foreach (ObjInfo itemInfo in tempShowInfoList) 87 //{ 88 // Debug.Log(itemInfo.mRelativePath + " " + itemInfo.mComType); 89 //} 90 //-- 91 92 string luaFilePath = Application.dataPath + "/LocalResources/Lua/UI"; 93 if (!Directory.Exists(luaFilePath)) Directory.CreateDirectory(luaFilePath); 94 string luaClassName = "Lua" + selectPrefab.name; 95 string luaFile = luaFilePath + "/" + luaClassName + ".lua.txt"; 96 97 if(System.IO.File.Exists(luaFile)) 98 { 99 Debug.LogError("exit this file! "); 100 return; 101 } 102 103 using (FileStream fs = new FileStream(luaFile, FileMode.Create)) 104 { 105 using (StreamWriter sw = new StreamWriter(fs)) 106 { 107 //开始写入 Window 108 sw.WriteLine("\n"); 109 sw.WriteLine("local " + luaClassName + " = Class(\"" + luaClassName + "\" , UICtrls.Window)"); 110 //ctor: 111 sw.WriteLine("\n"); 112 sw.WriteLine("function " + luaClassName + ":ctor()"); 113 sw.WriteLine("\tself:_initUI()"); 114 sw.WriteLine("end\n"); 115 //--BEGIN---_initUI()--- 116 sw.WriteLine("function " + luaClassName + ":_initUI()"); 117 118 foreach (ObjInfo itemInfo in tempShowInfoList) 119 { 120 string tempPrefix = string.Empty; 121 exportPrefixDict.TryGetValue(itemInfo.mComType, out tempPrefix); 122 if (tempPrefix == string.Empty) 123 { 124 Debug.LogError("BeginExport exportPrefixDict cannot find key!!!" + itemInfo.mComType); 125 return; 126 } 127 sw.WriteLine("\tself.m" + itemInfo.mObjectName + "="+tempPrefix+"(self,\"" +itemInfo.mRelativePath + "\")"); 128 if(itemInfo.IsButton()) 129 { 130 sw.WriteLine("\tself.m" + itemInfo.mObjectName + ":addEventClick(self." + itemInfo.GetButtonFuncName() + ")"); 131 } 132 } 133 sw.WriteLine("end\n"); 134 //--END---_initUI()--- 135 136 //destroy: 137 sw.WriteLine("function " + luaClassName + ":destroy()"); 138 sw.WriteLine("\t" + luaClassName + ".super.destroy(self)"); 139 sw.WriteLine("end\n"); 140 //show: 141 sw.WriteLine("function " + luaClassName + ":show(param)"); 142 sw.WriteLine("\t" + "--pass"); 143 sw.WriteLine("end\n"); 144 //extra function: 145 foreach (ObjInfo itemInfo in tempShowInfoList) 146 { 147 if (itemInfo.IsButton()) 148 { 149 sw.WriteLine("function " + luaClassName + ":"+ itemInfo.GetButtonFuncName()+"(sender)"); 150 sw.WriteLine("--pass"); 151 sw.WriteLine("end\n"); 152 } 153 } 154 //end: 155 sw.WriteLine("return " + luaClassName); 156 157 Debug.Log(luaFile + " generate complete ! "); 158 AssetDatabase.Refresh(); 159 } 160 } 161 162 } 163 164 165 class ObjInfo 166 { 167 public ObjInfo(string objName, string path, CompontType comType) 168 { 169 mObjectName = objName; 170 mRelativePath = path; 171 mComType = comType; 172 } 173 public string mObjectName = string.Empty; 174 public string mRelativePath = string.Empty; 175 public CompontType mComType = CompontType.Panel; 176 public bool IsButton() 177 { 178 return mComType == CompontType.Button; 179 } 180 public string GetButtonFuncName() 181 { 182 return "on" + mObjectName + "Click"; 183 } 184 185 } 186 187 static void WriteInitUI() 188 { 189 190 } 191 192 static string GetRelativePath(GameObject childNode, GameObject rootNode) 193 { 194 if (childNode == null || rootNode == null) 195 { 196 Debug.LogError("getRelativePath() object null!!!"); 197 return string.Empty; 198 } 199 if (childNode == rootNode) 200 { 201 Debug.LogError("is rootNode rootNode cannot choose!!!"); 202 return string.Empty; 203 } 204 string resultPath = childNode.name; 205 GameObject itemObj = childNode.transform.parent.gameObject; 206 for (; itemObj.name != rootNode.name; itemObj = itemObj.transform.parent.gameObject) 207 { 208 resultPath = itemObj.name + "/" + resultPath; 209 } 210 return resultPath; 211 } 212 213 static CompontType GetComType(GameObject resultObject) 214 { 215 CompontType tempType = CompontType.Panel; 216 if (resultObject.GetComponent<Button>() != null) 217 { 218 tempType = CompontType.Button; 219 } 220 else if (resultObject.GetComponent<Animator>() != null) 221 { 222 tempType = CompontType.Ain; 223 } 224 else if (resultObject.GetComponent<Toggle>() != null) 225 { 226 tempType = CompontType.Toggle; 227 } 228 else if (resultObject.GetComponent<InputField>() != null) 229 { 230 tempType = CompontType.Input; 231 } 232 else if (resultObject.GetComponent<Image>() != null) 233 { 234 tempType = CompontType.Image; 235 } 236 else if (resultObject.GetComponent<Text>() != null) 237 { 238 tempType = CompontType.Label; 239 } 240 else if (resultObject.GetComponent<Slider>() != null) 241 { 242 tempType = CompontType.Slider; 243 } 244 else if (resultObject.GetComponent<RawImage>() != null) 245 { 246 tempType = CompontType.RawImage; 247 } 248 else if (resultObject.GetComponent<Dropdown>() != null) 249 { 250 tempType = CompontType.Dropdown; 251 } 252 else 253 { 254 tempType = CompontType.Panel; 255 } 256 return tempType; 257 } 258 259 260 261 262 static void getGameObjectListRecursive(GameObject gameObject, ref List<GameObject> result, int maxDepth = int.MaxValue) 263 { 264 result.Add(gameObject); 265 if (maxDepth > 0) 266 { 267 Transform transform = gameObject.transform; 268 for (int i = transform.childCount - 1; i >= 0; i--) 269 getGameObjectListRecursive(transform.GetChild(i).gameObject, ref result, maxDepth - 1); 270 } 271 } 272 273 274 } 275 }

猜你喜欢

转载自www.cnblogs.com/sun-shadow/p/12178433.html