├── .gitattributes ├── .gitignore ├── README.md ├── README.md.meta ├── UICodeBuilderConfig.cs ├── UICodeBuilderConfig.cs.meta ├── UICodeBuilderWindow.cs ├── UICodeBuilderWindow.cs.meta ├── icon.png ├── icon.png.meta ├── screenshots.meta └── screenshots ├── 01.png └── 01.png.meta /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | [Ll]ibrary/ 2 | [Tt]emp/ 3 | [Oo]bj/ 4 | [Bb]uild/ 5 | [Bb]uilds/ 6 | Assets/AssetStoreTools* 7 | 8 | # Visual Studio cache directory 9 | .vs/ 10 | 11 | # Autogenerated VS/MD/Consulo solution and project files 12 | ExportedObj/ 13 | .consulo/ 14 | *.csproj 15 | *.unityproj 16 | *.sln 17 | *.suo 18 | *.tmp 19 | *.user 20 | *.userprefs 21 | *.pidb 22 | *.booproj 23 | *.svd 24 | *.pdb 25 | *.opendb 26 | *.VC.db 27 | 28 | # Unity3D generated meta files 29 | *.pidb.meta 30 | *.pdb.meta 31 | 32 | # Unity3D Generated File On Crash Reports 33 | sysinfo.txt 34 | 35 | # Builds 36 | *.apk 37 | *.unitypackage 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unity-UICodeBuilder🍹 2 | 3 | ![01.png](https://github.com/Yiiip/Unity-UICodeBuilder/blob/master/screenshots/01.png) 4 | 5 | You can modify the superclass and interface as well as code content for your own framework style. The auto generated code content is defined in config file. 6 | 7 | Note: To use this tool, you must add [rotorz/unity3d-reorderable-list](https://github.com/rotorz/unity3d-reorderable-list) dependency manually. 8 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7d275226a9271a04b95b4806942e0b2d 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /UICodeBuilderConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace LYP.UICodeBuilder 6 | { 7 | public class UICodeBuilderConfig : MonoBehaviour 8 | { 9 | public enum EventWidgetType 10 | { 11 | Button, 12 | Toggle, 13 | Slider, 14 | InputField, 15 | ScrollRect, 16 | Scrollbar, 17 | Dropdown, 18 | } 19 | 20 | public enum SuperclassIndex 21 | { 22 | MonoBehaviour, 23 | BaseView, 24 | NONE 25 | } 26 | 27 | public enum InterfaceIndex 28 | { 29 | ViewHolder 30 | } 31 | 32 | public static Dictionary eventDelegateParamDic = new Dictionary 33 | { 34 | { "Toggle", "bool" }, 35 | { "Slider", "float" }, 36 | { "InputField", "string" }, 37 | { "ScrollRect", "Vector2" }, 38 | { "Scrollbar", "float" }, 39 | { "Dropdown", "int" }, 40 | }; 41 | 42 | #region cs代码格式 43 | public static string codeAnnotation = 44 | @"/** 45 | * Powered by UICodeBuilder. 46 | * Author : " + System.Environment.UserName + @" 47 | * Date : " + System.DateTime.Now.ToString("yyyy-MM-dd") + @" 48 | * Time : " + System.DateTime.Now.ToString("t") + @" 49 | * Description: 50 | * (This file is auto generated by UICodeBuilder tool. You can edit anywhere.) 51 | */"; 52 | public const string regionStartFmt = "\n\t#region {0}\n"; 53 | public const string regionEnd = "\t#endregion\n"; 54 | 55 | public static string statementRegion = string.Format(regionStartFmt, "UI Variable Statement"); 56 | public static string eventRegion = string.Format(regionStartFmt, "UI Event Register"); 57 | public static string assignRegion = string.Format(regionStartFmt, "UI Variable Assignment"); 58 | 59 | public const string methodStartFmt = "\tprivate void {0}()\n\t{{\n"; //'{'要转义 60 | public const string methodEnd = "\n\t}\n"; 61 | 62 | public const string ifGoStartFmt = "\t\tif (go == {0}.gameObject)\n\t\t{{"; 63 | public const string ifelseGoStartFmt = "\n\t\telse if (go == {0}.gameObject)\n\t\t{{"; 64 | public const string ifEnd = "\n\t\t}"; 65 | 66 | public const string usingNamespace = "\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing UnityEngine.UI;\n"; 67 | public const string usingBaseViewNamespace = "using LYP.UI;\n"; 68 | public const string classMonoStart = "\npublic class {0} : MonoBehaviour{1}\n{{\n"; 69 | public const string classBaseViewStart = "\npublic class {0} : BaseView{1}\n{{\n"; 70 | public const string classStart = "\npublic class {0}{1}\n{{\n"; 71 | public const string classEnd = "\n}\n"; 72 | public const string methodAnnotation = "\n\t/// \n\t/// {0}\n\t/// \n"; 73 | 74 | #region 序列化初始化代码格式 75 | //控件遍历声明,0:类型 1:名称 76 | public const string serilStateCodePrivateFmt = "\t[SerializeField] private {0} {1};\n"; 77 | public const string serilStateCodePublicFmt = "\tpublic {0} {1};\n"; 78 | 79 | public const string onClickSerilCode = "\t\t{0}.onClick.AddListener(On{1}Clicked);\n"; 80 | public const string onClickSerilCodeForBaseView = "\t\tEventTriggerListener.Get({0}).onClick += OnBtnClick;\n"; 81 | public const string onValueChangeSerilCode = "\n\t\t{0}.onValueChanged.AddListener(On{1}ValueChanged);"; 82 | 83 | public const string btnCallbackSerilCode = "\n\tprivate void On{0}Clicked()\n\t{{\n\t}}\n"; 84 | public const string eventCallbackSerilCode = "\n\tprivate void On{0}ValueChanged({1} value)\n\t{{\n\t}}\n"; 85 | public const string onClickedCallbackSerilCode = "\n\tprivate void OnBtnClick(GameObject go)\n\t{\n"; 86 | #endregion 87 | 88 | #region 控件查找赋值格式 89 | public const string assignCodeFmt = "\t\t{0} = transform.Find(\"{1}\").GetComponent<{2}>();\n"; 90 | public const string assignGameObjectCodeFmt = "\t\t{0} = transform.Find(\"{1}\").gameObject;\n"; 91 | //根物体上挂载的控件 92 | public const string assignRootCodeFmt = "\t\t{0} = transform.GetComponent<{1}>();\n"; 93 | #endregion 94 | 95 | #region 查找初始化代码格式 96 | public const string stateTransform = "\tprivate Transform transform;\n"; 97 | public const string stateCodePrivateFmt = "\tprivate {0} {1};\n"; 98 | public const string stateCodePublicFmt = "\tpublic {0} {1};\n"; 99 | public const string assignTransform = "\t\t//assign transform by your ui framework\n\t\t//transform = ;\n"; 100 | #endregion 101 | 102 | #region 其他结构型代码 103 | public const string viewholderSetEmpty = "\n\tpublic void SetEmpty()\n\t{\n\t}\n"; 104 | public const string baseviewContextClass = "\npublic class {0}Context : BaseContext\n{{\n\t//Please add a GameViewType manually for the error below...\n\tpublic {0}Context() : base(GameViewType.{0}) {{ }}\n}}\n"; 105 | public const string baseviewStart = "\n\tprotected override void Start()\n\t{\n\t\tbase.Start();\n\t\t//You can apply this following code or delete it.\n\t\t//InitData();\n\t\t//InitViews();\n\t\t//InitEvents();\n\t}\n"; 106 | public const string baseviewOnEnter = "\n\tpublic override void OnEnter(BaseContext currentContext)\n\t{\n\t\tbase.Show();\n\t}\n"; 107 | public const string baseviewOnExit = "\n\tpublic override void OnExit(BaseContext currentContext)\n\t{\n\t\tbase.Hide();\n\t}\n"; 108 | public const string baseviewOnPause = "\n\tpublic override void OnPause(BaseContext currentContext)\n\t{\n\t\tbase.Hide();\n\t}\n"; 109 | public const string baseviewOnResume = "\n\tpublic override void OnResume(BaseContext lattContext)\n\t{\n\t\tbase.Show();\n\t}\n"; 110 | #endregion 111 | 112 | #endregion 113 | } 114 | } -------------------------------------------------------------------------------- /UICodeBuilderConfig.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c6d35f5d22541974bb9ff974834d229b 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /UICodeBuilderWindow.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by YingpengLiu. 3 | * 4 | * Date: 2019-01-07 5 | * Description: UI代码结构自动生成工具 6 | */ 7 | 8 | using System; 9 | using System.Collections; 10 | using System.Collections.Generic; 11 | using System.IO; 12 | using System.Reflection; 13 | using System.Text; 14 | using Rotorz.Games.Collections; 15 | using UnityEditor; 16 | using UnityEditorInternal; 17 | using UnityEngine; 18 | using UnityEngine.Events; 19 | using UnityEngine.EventSystems; 20 | using UnityEngine.UI; 21 | 22 | namespace LYP.UICodeBuilder 23 | { 24 | public class UICodeBuilderWindow : EditorWindow 25 | { 26 | private const string MENU_TITLE = "UI Code Builder"; 27 | private const string WIN_TITLE = "UI Builder"; 28 | private static string iconPath = "Assets/Editor/UI/UICodeBuilder/icon.png"; 29 | private static string[] arrSuperclassNames = new string[] 30 | { 31 | "MonoBehaviour", 32 | "BaseView", 33 | "NONE" 34 | }; 35 | private static string[] arrInterfaceNames = new string[] 36 | { 37 | "ViewHolder" 38 | }; 39 | private static string[] arrVarAccessNames = new string[] 40 | { 41 | "public", 42 | "private" 43 | }; 44 | private static UICodeBuilderWindow mWindow = null; 45 | private SerializedObject serializedObj; 46 | 47 | private float halfViewWidth; 48 | private Vector2 scrollWidgetPos; 49 | private Vector2 scrollCustomObjPos; 50 | private Vector2 scrollTextPos; 51 | private int selectedTabIndex = 0; 52 | private int selectedPopUpSuperclassIndex = (int) UICodeBuilderConfig.SuperclassIndex.MonoBehaviour; 53 | private int selectedPopUpVarAccessIndex = 0; 54 | 55 | private StringBuilder codeStateText; 56 | private StringBuilder codeStructureText; 57 | private StringBuilder codeEventText; 58 | private StringBuilder codeAssignText; 59 | private StringBuilder codeAllText; 60 | 61 | //选择的UI根节点 62 | private GameObject root; 63 | //UI控件列表 64 | private List uiWidgets = new List(); 65 | //UI自定义对象列表 66 | private List uiObjects = new List(); 67 | 68 | //需要注册事件的控件,可通过toggle选择 69 | private Dictionary toogleDicEventWidgets = new Dictionary(); 70 | //需要实现的接口 71 | private Dictionary toogleDicInterfaces = new Dictionary(); 72 | 73 | //变量编号 74 | private int variableNum; 75 | //缓存所有变量名和对应控件对象,对重名作处理 76 | private Dictionary variableNameDic = new Dictionary(); 77 | //保存的类名 78 | private string className; 79 | //脚本组件类型 80 | private Type scriptType; 81 | 82 | private string regionStartFmt { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.regionStartFmt : ""; } } 83 | private string regionEnd { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.regionEnd : ""; } } 84 | private string statementRegion { get { return UICodeBuilderConfig.statementRegion; } } 85 | private string eventRegion { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.eventRegion : ""; } } 86 | private string assignRegion { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.assignRegion : ""; } } 87 | private string methodStartFmt { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.methodStartFmt : ""; } } 88 | private string methodEnd { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.methodEnd : ""; } } 89 | private string assignCodeFmt { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.assignCodeFmt : ""; } } 90 | private string assignGameObjectCodeFmt { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.assignGameObjectCodeFmt : ""; } } 91 | private string assignRootCodeFmt { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.assignRootCodeFmt : ""; } } 92 | private string onClickSerilCode { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.onClickSerilCode : ""; } } 93 | private string onClickSerilCodeForBaseView { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.onClickSerilCodeForBaseView : ""; } } 94 | private string onValueChangeSerilCode { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.onValueChangeSerilCode : ""; } } 95 | private string btnCallbackSerilCode { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.btnCallbackSerilCode : ""; } } 96 | private string eventCallbackSerilCode { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.eventCallbackSerilCode : ""; } } 97 | private string onClickedCallbackSerilCode { get { return selectedTabIndex == 0 ? UICodeBuilderConfig.onClickedCallbackSerilCode : ""; } } 98 | 99 | //------------------------------------------------------------------------------------------ 100 | [MenuItem("Tools/UI/" + MENU_TITLE)] 101 | private static void ShowWindow() 102 | { 103 | if (mWindow == null) 104 | { 105 | mWindow = GetWindow(); 106 | } 107 | 108 | Texture2D icon = EditorGUIUtility.Load(iconPath) as Texture2D; 109 | mWindow.titleContent = new GUIContent(WIN_TITLE); 110 | mWindow.titleContent.image = icon; 111 | mWindow.Show(); 112 | } 113 | 114 | void OnEnable() 115 | { 116 | serializedObj = new SerializedObject(this); 117 | } 118 | 119 | void OnGUI() 120 | { 121 | serializedObj.Update(); 122 | 123 | if (mWindow == null) 124 | { 125 | mWindow = GetWindow(); 126 | } 127 | halfViewWidth = EditorGUIUtility.currentViewWidth / 2f; 128 | // halfViewHeight = mWindow.position.height / 2f; 129 | 130 | using(new EditorGUILayout.HorizontalScope()) 131 | { 132 | //左半部分 133 | using(EditorGUILayout.VerticalScope vScope = new EditorGUILayout.VerticalScope(GUILayout.Width(halfViewWidth))) 134 | { 135 | GUI.backgroundColor = Color.white; 136 | Rect rect = vScope.rect; 137 | rect.height = mWindow.position.height; 138 | GUI.Box(rect, ""); 139 | 140 | DrawSelectUI(); 141 | DrawFindWidget(); 142 | DrawWidgetList(); 143 | DrawCustomObjectList(); 144 | } 145 | //右半部分 146 | using(new EditorGUILayout.VerticalScope(GUILayout.Width(halfViewWidth))) 147 | { 148 | DrawCodeGenerateTitle(); 149 | DrawCodeGenerateTabs(); 150 | } 151 | } 152 | 153 | serializedObj.ApplyModifiedProperties(); 154 | } 155 | 156 | private void DrawSelectUI() 157 | { 158 | EditorGUILayout.Space(); 159 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 160 | { 161 | GUI.backgroundColor = Color.white; 162 | Rect rect = hScope.rect; 163 | rect.height = EditorGUIUtility.singleLineHeight; 164 | GUI.Box(rect, ""); 165 | 166 | EditorGUILayout.LabelField("Selected UI Node:", GUILayout.Width(halfViewWidth / 3f)); 167 | GameObject lastRoot = root; 168 | root = EditorGUILayout.ObjectField(root, typeof(GameObject), true) as GameObject; 169 | 170 | if (lastRoot != null && lastRoot != root) 171 | { 172 | uiWidgets.Clear(); 173 | uiObjects.Clear(); 174 | } 175 | } 176 | } 177 | 178 | private void DrawFindWidget() 179 | { 180 | EditorGUILayout.Space(); 181 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 182 | { 183 | GUI.backgroundColor = Color.white; 184 | Rect rect = hScope.rect; 185 | rect.height = EditorGUIUtility.singleLineHeight; 186 | GUI.Box(rect, ""); 187 | 188 | if (GUILayout.Button("SCAN UI Node", GUILayout.Width(halfViewWidth / 2f))) 189 | { 190 | ScanWidgets(); 191 | } 192 | 193 | if (GUILayout.Button("Clear Widgets")) 194 | { 195 | uiWidgets.Clear(); 196 | toogleDicEventWidgets.Clear(); 197 | } 198 | if (GUILayout.Button("Clear Customized")) 199 | { 200 | uiObjects.Clear(); 201 | toogleDicEventWidgets.Clear(); 202 | } 203 | } 204 | } 205 | 206 | private void DrawWidgetList() 207 | { 208 | EditorGUILayout.Space(); 209 | 210 | ReorderableListGUI.Title("UI Widgets"); 211 | scrollWidgetPos = EditorGUILayout.BeginScrollView(scrollWidgetPos); 212 | ReorderableListGUI.ListField(uiWidgets, DrawWidget); 213 | EditorGUILayout.EndScrollView(); 214 | } 215 | 216 | private UIBehaviour DrawWidget(Rect position, UIBehaviour item) 217 | { 218 | item = (UIBehaviour) EditorGUI.ObjectField(position, item, typeof(UIBehaviour), true); 219 | return item; 220 | } 221 | 222 | private void DrawCustomObjectList() 223 | { 224 | EditorGUILayout.Space(); 225 | 226 | ReorderableListGUI.Title("Customized UI Objects"); 227 | scrollCustomObjPos = EditorGUILayout.BeginScrollView(scrollCustomObjPos); 228 | ReorderableListGUI.ListField(uiObjects, DrawCustomObject); 229 | EditorGUILayout.EndScrollView(); 230 | } 231 | 232 | private GameObject DrawCustomObject(Rect position, GameObject item) 233 | { 234 | item = (GameObject) EditorGUI.ObjectField(position, item, typeof(GameObject), true); 235 | return item; 236 | } 237 | 238 | private void DrawCodeGenerateTitle() 239 | { 240 | EditorGUILayout.Space(); 241 | using(var hScope = new EditorGUILayout.HorizontalScope(GUILayout.Height(EditorGUIUtility.singleLineHeight))) 242 | { 243 | GUI.backgroundColor = Color.white; 244 | Rect rect = hScope.rect; 245 | GUI.Box(rect, ""); 246 | 247 | EditorGUILayout.LabelField("UI CODE BUILDER"); 248 | } 249 | } 250 | 251 | private void DrawCodeGenerateTabs() 252 | { 253 | EditorGUILayout.Space(); 254 | 255 | selectedTabIndex = GUILayout.Toolbar(selectedTabIndex, new string[] { "C#" }); 256 | 257 | switch (selectedTabIndex) 258 | { 259 | case 0: 260 | DrawCSPage(); 261 | break; 262 | default: 263 | break; 264 | } 265 | } 266 | 267 | private void DrawCSPage() 268 | { 269 | EditorGUILayout.Space(); 270 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 271 | { 272 | GUILayout.Label("Superclass:", GUILayout.Width(90f)); 273 | selectedPopUpSuperclassIndex = EditorGUILayout.Popup(selectedPopUpSuperclassIndex, arrSuperclassNames); 274 | } 275 | EditorGUILayout.Space(); 276 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 277 | { 278 | GUILayout.Label("Interface:", GUILayout.Width(90f)); 279 | foreach (string name in arrInterfaceNames) 280 | { 281 | if (!toogleDicInterfaces.ContainsKey(name)) 282 | { 283 | toogleDicInterfaces.Add(name, false); 284 | } 285 | } 286 | foreach (string name in arrInterfaceNames) 287 | { 288 | toogleDicInterfaces[name] = EditorGUILayout.ToggleLeft(name, toogleDicInterfaces[name], GUILayout.Width(halfViewWidth / arrInterfaceNames.Length)); 289 | } 290 | } 291 | 292 | EditorGUILayout.Space(); 293 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 294 | { 295 | if (GUILayout.Button("1. Declare Variables", GUILayout.Width(halfViewWidth / 3f))) 296 | { 297 | BuildStatementCode(); 298 | } 299 | selectedPopUpVarAccessIndex = EditorGUILayout.Popup(selectedPopUpVarAccessIndex, arrVarAccessNames); 300 | } 301 | 302 | EditorGUILayout.Space(); 303 | using(EditorGUILayout.VerticalScope vScope = new EditorGUILayout.VerticalScope()) 304 | { 305 | GUI.backgroundColor = Color.white; 306 | GUI.Box(vScope.rect, ""); 307 | 308 | EditorGUILayout.LabelField("Select widgets to add events:"); 309 | DrawEventWidget(); 310 | 311 | EditorGUILayout.Space(); 312 | if (GUILayout.Button("2. Add Events", GUILayout.Width(halfViewWidth / 3f))) 313 | { 314 | BuildEventsCode(); 315 | } 316 | } 317 | 318 | EditorGUILayout.Space(); 319 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 320 | { 321 | if (GUILayout.Button("3. Find View By Name", GUILayout.Width(halfViewWidth / 2f))) 322 | { 323 | BuildAssignmentCode(); 324 | } 325 | if (GUILayout.Button("4. CREATE & SAVE Script", GUILayout.Width(halfViewWidth / 2f))) 326 | { 327 | CreateCsUIScript(); 328 | } 329 | } 330 | 331 | EditorGUILayout.Space(); 332 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 333 | { 334 | if (selectedPopUpSuperclassIndex != (int) UICodeBuilderConfig.SuperclassIndex.NONE) 335 | { 336 | if (GUILayout.Button("5. Add Script Component", GUILayout.Width(halfViewWidth / 2f))) 337 | { 338 | AddScriptComponent(); 339 | } 340 | if (GUILayout.Button("6. Bind Refrences", GUILayout.Width(halfViewWidth / 2f))) 341 | { 342 | BindSerializeWidgetRefrences(); 343 | } 344 | } 345 | } 346 | 347 | DrawPreviewText(); 348 | } 349 | 350 | private void DrawEventWidget() 351 | { 352 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 353 | { 354 | foreach (var elem in System.Enum.GetValues(typeof(UICodeBuilderConfig.EventWidgetType))) 355 | { 356 | for (int i = 0; i < uiWidgets.Count; i++) 357 | { 358 | if (uiWidgets[i] == null) 359 | { 360 | continue; 361 | } 362 | 363 | Type type = uiWidgets[i].GetType(); 364 | if (type == null) 365 | { 366 | Debug.LogWarning("Type error! " + uiWidgets[i].name); 367 | continue; 368 | } 369 | 370 | if (type.Name == elem.ToString() && !toogleDicEventWidgets.ContainsKey(type.Name)) 371 | { 372 | toogleDicEventWidgets.Add(type.Name, true); 373 | } 374 | } 375 | } 376 | 377 | //移出控件不存在的事件类型 378 | List notExist = new List(); 379 | foreach (string tName in toogleDicEventWidgets.Keys) 380 | { 381 | bool exist = false; 382 | for (int i = 0; i < uiWidgets.Count; i++) 383 | { 384 | Type type = uiWidgets[i].GetType(); 385 | if (type != null && type.Name == tName) 386 | { 387 | exist = true; 388 | break; 389 | } 390 | } 391 | if (!exist) 392 | { 393 | notExist.Add(tName); 394 | } 395 | } 396 | foreach (string name in notExist) 397 | { 398 | toogleDicEventWidgets.Remove(name); 399 | } 400 | notExist.Clear(); 401 | 402 | //绘制toggle,注意不能遍历dic的同时赋值 403 | List list = new List(toogleDicEventWidgets.Keys); 404 | foreach (string name in list) 405 | { 406 | toogleDicEventWidgets[name] = EditorGUILayout.ToggleLeft(name, toogleDicEventWidgets[name], GUILayout.Width(halfViewWidth / 7f)); 407 | } 408 | } 409 | } 410 | 411 | private void DrawPreviewText() 412 | { 413 | EditorGUILayout.Space(); 414 | using(EditorGUILayout.HorizontalScope hScope = new EditorGUILayout.HorizontalScope()) 415 | { 416 | if (GUILayout.Button("Copy Code", GUILayout.Width(halfViewWidth * 0.5f))) 417 | { 418 | TextEditor p = new TextEditor(); 419 | if (codeStateText != null) 420 | { 421 | codeAllText = new StringBuilder(codeStateText.ToString()); 422 | codeAllText.Append(codeAssignText); 423 | codeAllText.Append(codeEventText); 424 | p.text = codeAllText.ToString(); 425 | p.OnFocus(); 426 | p.Copy(); 427 | 428 | EditorUtility.DisplayDialog("Tips", "Copy succeed!", "OK"); 429 | } 430 | else 431 | { 432 | EditorUtility.DisplayDialog("Tips", "Copy nothing! Please check 1st step.", "OK"); 433 | } 434 | } 435 | if (GUILayout.Button("Clear Code(2)", GUILayout.Width(halfViewWidth * 0.25f))) 436 | { 437 | if (codeEventText != null) 438 | { 439 | codeEventText.Remove(0, codeEventText.Length); 440 | } 441 | } 442 | if (GUILayout.Button("Clear Code(3)", GUILayout.Width(halfViewWidth * 0.25f))) 443 | { 444 | if (codeAssignText != null) 445 | { 446 | codeAssignText.Remove(0, codeAssignText.Length); 447 | } 448 | } 449 | } 450 | 451 | using(var ver = new EditorGUILayout.VerticalScope()) 452 | { 453 | GUI.backgroundColor = new Color(43f/255f, 43f/255f, 43f/255f); 454 | GUI.Box(ver.rect, ""); 455 | 456 | EditorGUILayout.HelpBox("Code Preview:", MessageType.None); 457 | 458 | using(var scr = new EditorGUILayout.ScrollViewScope(scrollTextPos)) 459 | { 460 | scrollTextPos = scr.scrollPosition; 461 | 462 | GUIStyle cssNormalText = new GUIStyle(); 463 | cssNormalText.normal.textColor = new Color(240f/255f, 240f/255f, 240f/255f); 464 | 465 | GUIStyle cssStructureText = new GUIStyle(); 466 | cssStructureText.normal.textColor = new Color(70f/255f, 149f/255f, 214f/255f); 467 | 468 | GUILayout.Label(GetNamespaceString(), cssNormalText); 469 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 470 | { 471 | GUILayout.Label(string.Format(UICodeBuilderConfig.baseviewContextClass, "YourClazz"), cssStructureText); 472 | } 473 | GUILayout.Label(GetClazzString("YourClazz", GetInterfacesString()), cssNormalText); 474 | 475 | if (codeStateText != null && !string.IsNullOrEmpty(codeStateText.ToString()) && selectedTabIndex == 0) 476 | { 477 | GUIStyle cssStateText = new GUIStyle(); 478 | cssStateText.normal.textColor = new Color(254f/255f, 217f/255f, 92f/255f); 479 | GUILayout.Label(codeStateText.ToString(), cssStateText); 480 | } 481 | 482 | if (codeStructureText != null && !string.IsNullOrEmpty(codeStructureText.ToString())) 483 | { 484 | GUILayout.Label(codeStructureText.ToString(), cssStructureText); 485 | } 486 | 487 | if (codeAssignText != null && !string.IsNullOrEmpty(codeAssignText.ToString())) 488 | { 489 | GUIStyle cssAssignText = new GUIStyle(); 490 | cssAssignText.normal.textColor = new Color(40f/255f, 204f/255f, 117f/255f); 491 | GUILayout.Label(codeAssignText.ToString(), cssAssignText); 492 | } 493 | 494 | if (codeEventText != null && !string.IsNullOrEmpty(codeEventText.ToString())) 495 | { 496 | GUIStyle cssEventText = new GUIStyle(); 497 | cssEventText.normal.textColor = new Color(250f/255f, 110f/255f, 87f/255f); 498 | GUILayout.Label(codeEventText.ToString(), cssEventText); 499 | } 500 | 501 | GUILayout.Label(UICodeBuilderConfig.classEnd, cssNormalText); 502 | } 503 | } 504 | } 505 | 506 | private bool IsMonoBased() 507 | { 508 | return (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.MonoBehaviour) || 509 | (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView); 510 | } 511 | 512 | private bool IsPublic() 513 | { 514 | return (arrVarAccessNames[selectedPopUpVarAccessIndex] == "public"); 515 | } 516 | 517 | private bool IsToogledViewHolder() 518 | { 519 | return toogleDicInterfaces[arrInterfaceNames[(int) UICodeBuilderConfig.InterfaceIndex.ViewHolder]]; 520 | } 521 | 522 | private bool CheckSelectedRoot() 523 | { 524 | if (root == null) 525 | { 526 | EditorUtility.DisplayDialog("Tips", "Please select an UI node!", "OK"); 527 | return false; 528 | } 529 | return true; 530 | } 531 | 532 | private bool CheckScriptSaved() 533 | { 534 | if (root == null || string.IsNullOrEmpty(className)) 535 | { 536 | EditorUtility.DisplayDialog("Warning", "Please check step 1~4 firstly.", "OK"); 537 | return false; 538 | } 539 | return true; 540 | } 541 | 542 | private bool CheckIsAddedScriptComponent() 543 | { 544 | if (scriptType == null) 545 | { 546 | EditorUtility.DisplayDialog("Warning", "Please check step 1~5 firstly.", "OK"); 547 | return false; 548 | } 549 | return true; 550 | } 551 | 552 | private bool CheckEditorIsCompiling() 553 | { 554 | if (EditorApplication.isCompiling) 555 | { 556 | EditorUtility.DisplayDialog("Warning", "Please wait for Editor compiling.", "OK"); 557 | return true; 558 | } 559 | return false; 560 | } 561 | 562 | private void ScanWidgets() 563 | { 564 | if (!CheckSelectedRoot()) 565 | { 566 | return; 567 | } 568 | 569 | uiWidgets.Clear(); 570 | RecursiveUI(root.transform, (tran) => 571 | { 572 | UIBehaviour[] widgets = tran.GetComponents(); 573 | for (int i = 0; i < widgets.Length; i++) 574 | { 575 | UIBehaviour widget = widgets[i]; 576 | if (widget != null && !ShouldFilterUIWidget(widget) && !uiWidgets.Contains(widget)) 577 | { 578 | uiWidgets.Add(widget); 579 | } 580 | } 581 | }); 582 | } 583 | 584 | private bool ShouldFilterUIWidget(UIBehaviour ui) 585 | { 586 | if (ui is Outline || ui is Shadow) 587 | { 588 | return true; 589 | } 590 | return false; 591 | } 592 | 593 | public void RecursiveUI(Transform parent, UnityAction callback) 594 | { 595 | if (callback != null) 596 | { 597 | callback(parent); 598 | } 599 | 600 | for (int i = 0; i < parent.childCount; i++) 601 | { 602 | Transform child = parent.GetChild(i); 603 | this.RecursiveUI(child, callback); 604 | } 605 | } 606 | 607 | private string VarNameFilter(string varName) 608 | { 609 | string result = varName; 610 | result = result.Replace(" ", ""); 611 | result = result.Replace("(", ""); 612 | result = result.Replace(")", ""); 613 | result = result.Replace(".", ""); 614 | result = result.Replace(",", ""); 615 | result = result.Replace("-", ""); 616 | result = result.Replace("+", ""); 617 | // Regex regNum = new Regex("^[0-9]"); 618 | // if (regNum.IsMatch(result)) 619 | // { 620 | // result = "ui" + result; 621 | // } 622 | return result; 623 | } 624 | 625 | private string BuildStatementCode() 626 | { 627 | variableNum = 0; 628 | variableNameDic.Clear(); 629 | 630 | codeStateText = null; 631 | codeStateText = new StringBuilder(); 632 | 633 | codeStateText.Append(UICodeBuilderConfig.statementRegion); 634 | //非mono类声明一个transform 635 | if (!IsMonoBased()) 636 | { 637 | codeStateText.Append(UICodeBuilderConfig.stateTransform); 638 | } 639 | 640 | //控件列表 641 | for (int i = 0; i < uiWidgets.Count; i++) 642 | { 643 | if (uiWidgets[i] == null) continue; 644 | 645 | Type type = uiWidgets[i].GetType(); 646 | if (type == null) 647 | { 648 | Debug.LogError("BuildUICode type error !"); 649 | return ""; 650 | } 651 | 652 | string typeName = type.Name; 653 | string prefixName = type.Name; 654 | string widgetName = uiWidgets[i].name; 655 | 656 | if (prefixName == "Image") { prefixName = "Img"; } 657 | else if (prefixName == "Button") { prefixName = "Btn"; } 658 | if (widgetName.StartsWith(prefixName) || widgetName.StartsWith(prefixName.ToLower())) 659 | { 660 | widgetName = widgetName.Remove(0, prefixName.Length); 661 | } 662 | 663 | string varName = string.Format("{0}_{1}", prefixName.ToLower(), widgetName); 664 | varName = VarNameFilter(varName); 665 | //重名处理 666 | if (variableNameDic.ContainsKey(varName)) 667 | { 668 | ++variableNum; 669 | varName += ("0" + variableNum); 670 | } 671 | variableNameDic.Add(varName, uiWidgets[i]); 672 | 673 | string varNameToShow = varName.Replace("_", ""); 674 | if (IsMonoBased()) 675 | { 676 | if (IsPublic()) 677 | { 678 | codeStateText.AppendFormat(UICodeBuilderConfig.serilStateCodePublicFmt, typeName, varNameToShow); 679 | } 680 | else 681 | { 682 | codeStateText.AppendFormat(UICodeBuilderConfig.serilStateCodePrivateFmt, typeName, varNameToShow); 683 | } 684 | } 685 | else 686 | { 687 | if (IsPublic()) 688 | { 689 | codeStateText.AppendFormat(UICodeBuilderConfig.stateCodePublicFmt, typeName, varNameToShow); 690 | } 691 | else 692 | { 693 | codeStateText.AppendFormat(UICodeBuilderConfig.stateCodePrivateFmt, typeName, varNameToShow); 694 | } 695 | } 696 | } 697 | //其他对象列表,目前都是GameObject 698 | for (int i = 0; i < uiObjects.Count; i++) 699 | { 700 | if (uiObjects[i] == null) continue; 701 | 702 | Type type = uiObjects[i].GetType(); 703 | if (type == null) 704 | { 705 | Debug.LogError("BuildUICode type error !"); 706 | return ""; 707 | } 708 | 709 | string typeName = type.Name; 710 | string varName = string.Format("obj_{0}", uiObjects[i].name); 711 | varName = VarNameFilter(varName); 712 | //重名处理 713 | if (variableNameDic.ContainsKey(varName)) 714 | { 715 | ++variableNum; 716 | varName += ("0" + variableNum); 717 | } 718 | variableNameDic.Add(varName, uiObjects[i]); 719 | 720 | string varNameToShow = varName.Replace("_", ""); 721 | if (IsMonoBased()) 722 | { 723 | if (IsPublic()) 724 | { 725 | codeStateText.AppendFormat(UICodeBuilderConfig.serilStateCodePublicFmt, typeName, varNameToShow); 726 | } 727 | else 728 | { 729 | codeStateText.AppendFormat(UICodeBuilderConfig.serilStateCodePrivateFmt, typeName, varNameToShow); 730 | } 731 | } 732 | else 733 | { 734 | if (IsPublic()) 735 | { 736 | codeStateText.AppendFormat(UICodeBuilderConfig.stateCodePublicFmt, typeName, varNameToShow); 737 | } 738 | else 739 | { 740 | codeStateText.AppendFormat(UICodeBuilderConfig.stateCodePrivateFmt, typeName, varNameToShow); 741 | } 742 | } 743 | } 744 | 745 | codeStateText.Append(UICodeBuilderConfig.regionEnd); 746 | 747 | codeStructureText = null; 748 | codeStructureText = new StringBuilder(); 749 | if (IsToogledViewHolder()) 750 | { 751 | codeStructureText.Append(UICodeBuilderConfig.viewholderSetEmpty); 752 | } 753 | 754 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 755 | { 756 | codeStructureText.Append(UICodeBuilderConfig.baseviewStart); 757 | codeStructureText.Append(UICodeBuilderConfig.baseviewOnEnter); 758 | codeStructureText.Append(UICodeBuilderConfig.baseviewOnExit); 759 | codeStructureText.Append(UICodeBuilderConfig.baseviewOnResume); 760 | codeStructureText.Append(UICodeBuilderConfig.baseviewOnPause); 761 | } 762 | 763 | // Debug.Log(codeStateText); 764 | // Debug.Log(codeInitialText); 765 | return codeStateText.ToString() + codeStructureText.ToString(); 766 | } 767 | 768 | private string BuildEventsCode() 769 | { 770 | codeEventText = null; 771 | codeEventText = new StringBuilder(); 772 | 773 | codeEventText.Append(eventRegion); 774 | codeEventText.AppendFormat(methodStartFmt, "InitEvents"); 775 | 776 | var tempBtnNames = new List(); 777 | 778 | bool hasEventWidget = false; //标识是否有控件注册了事件,动态增加换行符 779 | for (int i = 0; i < uiWidgets.Count; i++) 780 | { 781 | if (uiWidgets[i] == null) continue; 782 | 783 | //剔除不是事件或者是事件但未勾选toggle的控件 784 | string typeName = uiWidgets[i].GetType().Name; 785 | if (!toogleDicEventWidgets.ContainsKey(typeName) || toogleDicEventWidgets[typeName] == false) 786 | { 787 | continue; 788 | } 789 | 790 | foreach (string vName in variableNameDic.Keys) 791 | { 792 | if (uiWidgets[i].Equals(variableNameDic[vName])) 793 | { 794 | if (!string.IsNullOrEmpty(vName)) 795 | { 796 | string varName = vName; 797 | string varNameToShow = varName.Replace("_", ""); 798 | string methodName = varName.Substring(varName.IndexOf('_') + 1); 799 | if (uiWidgets[i] is Button) 800 | { 801 | if (!tempBtnNames.Contains(varNameToShow)) 802 | { 803 | tempBtnNames.Add(varNameToShow); 804 | } 805 | 806 | string onClickStr = ""; 807 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 808 | { 809 | onClickStr = string.Format(onClickSerilCodeForBaseView, varNameToShow); 810 | } 811 | else 812 | { 813 | onClickStr = string.Format(onClickSerilCode, varNameToShow, methodName); 814 | } 815 | 816 | if (hasEventWidget) 817 | { 818 | string str = codeEventText.ToString(); 819 | codeEventText.Insert(str.LastIndexOf(';') + 1, "\n" + onClickStr); 820 | } 821 | else 822 | { 823 | codeEventText.Append(onClickStr); 824 | } 825 | 826 | if (selectedPopUpSuperclassIndex != (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 827 | { 828 | codeEventText.AppendFormat(btnCallbackSerilCode, methodName); 829 | } 830 | hasEventWidget = true; 831 | } 832 | else 833 | { 834 | string addEventStr = string.Format(onValueChangeSerilCode, varNameToShow, methodName); 835 | if (hasEventWidget) 836 | { 837 | codeEventText.Insert(codeEventText.ToString().LastIndexOf(';') + 1, addEventStr); 838 | } 839 | else 840 | { 841 | codeEventText.Append(addEventStr); 842 | } 843 | 844 | string paramType = ""; 845 | foreach (string widgetType in UICodeBuilderConfig.eventDelegateParamDic.Keys) 846 | { 847 | if (typeName == widgetType) 848 | { 849 | paramType = UICodeBuilderConfig.eventDelegateParamDic[widgetType]; 850 | break; 851 | } 852 | } 853 | 854 | if (!string.IsNullOrEmpty(paramType)) 855 | { 856 | codeEventText.AppendFormat(eventCallbackSerilCode, methodName, paramType); 857 | } 858 | 859 | hasEventWidget = true; 860 | } 861 | } 862 | break; 863 | } 864 | } 865 | } 866 | 867 | string codeStr = codeEventText.ToString(); 868 | if (hasEventWidget) 869 | { 870 | codeEventText.Insert(codeStr.LastIndexOf(';') + 1, methodEnd); 871 | } 872 | else 873 | { 874 | codeEventText.Append(methodEnd); 875 | } 876 | 877 | //For BaseView.OnBtnClick(GameObject go) 878 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 879 | { 880 | codeEventText.Append(onClickedCallbackSerilCode); 881 | for (int i = 0; i < tempBtnNames.Count; i++) 882 | { 883 | if (i == 0) 884 | { 885 | codeEventText.AppendFormat(UICodeBuilderConfig.ifGoStartFmt, tempBtnNames[i]); 886 | } 887 | else 888 | { 889 | codeEventText.AppendFormat(UICodeBuilderConfig.ifelseGoStartFmt, tempBtnNames[i]); 890 | } 891 | codeEventText.Append(UICodeBuilderConfig.ifEnd); 892 | } 893 | codeEventText.Append(methodEnd); 894 | } 895 | 896 | codeEventText.Append(regionEnd); 897 | return codeEventText.ToString(); 898 | } 899 | 900 | private void BuildAssignmentCode() 901 | { 902 | if (!CheckSelectedRoot()) 903 | { 904 | return; 905 | } 906 | 907 | codeAssignText = new StringBuilder(); 908 | 909 | codeAssignText.Append(assignRegion); 910 | codeAssignText.AppendFormat(methodStartFmt, "InitViews"); 911 | if (!IsMonoBased() && selectedTabIndex == 0) 912 | { 913 | codeAssignText.Append(UICodeBuilderConfig.assignTransform); 914 | } 915 | 916 | Dictionary allPath = GetChildrenPaths(root); 917 | 918 | if (variableNameDic == null) 919 | { 920 | return; 921 | } 922 | 923 | //格式:变量名 = transform.Find("").Getcomponent<>(); 924 | foreach (string vName in variableNameDic.Keys) 925 | { 926 | object obj = variableNameDic[vName]; 927 | if (obj == null) continue; 928 | 929 | string varNameToShow = vName.Replace("_", ""); 930 | 931 | string path = ""; 932 | bool isRootComponent = false; 933 | foreach (Transform tran in allPath.Keys) 934 | { 935 | if (tran == null) continue; 936 | 937 | UIBehaviour behav = obj as UIBehaviour; 938 | if (behav != null) 939 | { 940 | //判断是否挂在根上,根上不需要路径 941 | isRootComponent = behav.gameObject == root; 942 | if (isRootComponent) break; 943 | 944 | if (behav.gameObject == tran.gameObject) 945 | { 946 | path = allPath[tran]; 947 | break; 948 | } 949 | } 950 | else 951 | { 952 | if (tran.gameObject == obj) 953 | { 954 | path = allPath[tran]; 955 | break; 956 | } 957 | } 958 | } 959 | 960 | if (obj is GameObject) 961 | { 962 | codeAssignText.AppendFormat(assignGameObjectCodeFmt, varNameToShow, path); 963 | } 964 | else 965 | { 966 | if (isRootComponent) 967 | { 968 | codeAssignText.AppendFormat(assignRootCodeFmt, varNameToShow, obj.GetType().Name); 969 | } 970 | else 971 | { 972 | codeAssignText.AppendFormat(assignCodeFmt, varNameToShow, path, obj.GetType().Name); 973 | } 974 | } 975 | } 976 | 977 | codeAssignText.Append(methodEnd); 978 | codeAssignText.Append(regionEnd); 979 | //Debug.Log(codeAssignText.ToString()); 980 | } 981 | 982 | private Dictionary GetChildrenPaths(GameObject rootGo) 983 | { 984 | Dictionary pathDic = new Dictionary(); 985 | string path = string.Empty; 986 | Transform[] tfArray = rootGo.GetComponentsInChildren(true); 987 | for (int i = 0; i < tfArray.Length; i++) 988 | { 989 | Transform node = tfArray[i]; 990 | 991 | string nodeName = node.name; 992 | while (node.parent != null && node.gameObject != rootGo && node.parent.gameObject != rootGo) 993 | { 994 | nodeName = string.Format("{0}/{1}", node.parent.name, nodeName); 995 | node = node.parent; 996 | } 997 | path += string.Format("{0}\n", nodeName); 998 | 999 | if (!pathDic.ContainsKey(tfArray[i])) 1000 | { 1001 | pathDic.Add(tfArray[i], nodeName); 1002 | } 1003 | } 1004 | //Debug.Log(path); 1005 | return pathDic; 1006 | } 1007 | 1008 | private void CreateCsUIScript() 1009 | { 1010 | string path = EditorPrefs.GetString("create_script_folder", ""); 1011 | path = EditorUtility.SaveFilePanel("Save Script", path, root.name + ".cs", "cs"); 1012 | if (string.IsNullOrEmpty(path)) return; 1013 | 1014 | int index = path.LastIndexOf('/'); 1015 | className = path.Substring(index + 1, path.LastIndexOf('.') - index - 1); 1016 | 1017 | StringBuilder scriptContent = new StringBuilder(); 1018 | scriptContent.Append(UICodeBuilderConfig.codeAnnotation); 1019 | scriptContent.Append(GetNamespaceString()); 1020 | 1021 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 1022 | { 1023 | scriptContent.AppendFormat(UICodeBuilderConfig.baseviewContextClass, className); 1024 | } 1025 | 1026 | string interfacesStr = GetInterfacesString(); 1027 | string clazzStr = GetClazzString(className, interfacesStr); 1028 | scriptContent.Append(clazzStr); 1029 | 1030 | scriptContent.Append(codeStateText); 1031 | scriptContent.Append(codeStructureText); 1032 | scriptContent.Append(codeAssignText); 1033 | scriptContent.Append(codeEventText); 1034 | 1035 | scriptContent.Append(UICodeBuilderConfig.classEnd); 1036 | 1037 | try 1038 | { 1039 | File.WriteAllText(path, scriptContent.ToString(), new UTF8Encoding(false)); 1040 | AssetDatabase.Refresh(); 1041 | 1042 | Debug.Log("Good job! A script is created at: " + path + ""); 1043 | EditorPrefs.SetString("create_script_folder", path); 1044 | } 1045 | catch (System.Exception e) 1046 | { 1047 | Debug.LogError(e.Message); 1048 | } 1049 | } 1050 | 1051 | private string GetNamespaceString() 1052 | { 1053 | string namespaceStr = UICodeBuilderConfig.usingNamespace; 1054 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 1055 | { 1056 | namespaceStr += UICodeBuilderConfig.usingBaseViewNamespace; 1057 | } 1058 | return namespaceStr; 1059 | } 1060 | 1061 | private string GetInterfacesString() 1062 | { 1063 | string interfaces = ""; 1064 | foreach (var kv in toogleDicInterfaces) 1065 | { 1066 | if (kv.Value) 1067 | { 1068 | interfaces += (", " + kv.Key); 1069 | } 1070 | } 1071 | 1072 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.NONE && 1073 | !interfaces.Equals("")) 1074 | { 1075 | int invalidSymbol = interfaces.IndexOf(','); 1076 | interfaces = interfaces.Substring(invalidSymbol + 1); 1077 | interfaces = " :" + interfaces; 1078 | } 1079 | 1080 | return interfaces; 1081 | } 1082 | 1083 | private string GetClazzString(string className, string interfaces) 1084 | { 1085 | string clazzStr = ""; 1086 | string clazzFormat = "{0}"; 1087 | if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.MonoBehaviour) 1088 | { 1089 | clazzFormat = UICodeBuilderConfig.classMonoStart; 1090 | } 1091 | else if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.BaseView) 1092 | { 1093 | clazzFormat = UICodeBuilderConfig.classBaseViewStart; 1094 | } 1095 | else if (selectedPopUpSuperclassIndex == (int) UICodeBuilderConfig.SuperclassIndex.NONE) 1096 | { 1097 | clazzFormat = UICodeBuilderConfig.classStart; 1098 | } 1099 | clazzStr = string.Format(clazzFormat, className, interfaces); 1100 | return clazzStr; 1101 | } 1102 | 1103 | private void AddScriptComponent() 1104 | { 1105 | if (CheckEditorIsCompiling() || !CheckScriptSaved()) 1106 | { 1107 | return; 1108 | } 1109 | 1110 | Assembly[] AssbyCustmList = System.AppDomain.CurrentDomain.GetAssemblies(); 1111 | Assembly asCSharp = null; 1112 | for (int i = 0; i < AssbyCustmList.Length; i++) 1113 | { 1114 | string assbyName = AssbyCustmList[i].GetName().Name; 1115 | if (assbyName == "Assembly-CSharp") 1116 | { 1117 | asCSharp = AssbyCustmList[i]; 1118 | break; 1119 | } 1120 | } 1121 | 1122 | scriptType = asCSharp.GetType(className); 1123 | if (scriptType == null) 1124 | { 1125 | EditorUtility.DisplayDialog("Warning", "Add script component failed! Please check your script is correct.", "OK"); 1126 | return; 1127 | } 1128 | else 1129 | { 1130 | Component targetComponent = root.GetComponent(scriptType); 1131 | if (targetComponent == null) 1132 | { 1133 | targetComponent = root.AddComponent(scriptType); 1134 | } 1135 | } 1136 | } 1137 | 1138 | private void BindSerializeWidgetRefrences() 1139 | { 1140 | if (CheckEditorIsCompiling() || !CheckScriptSaved() || !CheckIsAddedScriptComponent()) 1141 | { 1142 | return; 1143 | } 1144 | 1145 | Component targetComponent = root.GetComponent(scriptType); 1146 | if (targetComponent == null) 1147 | { 1148 | targetComponent = root.AddComponent(scriptType); 1149 | } 1150 | 1151 | //资源刷新以后variableNameDic被清空了= =再获取一遍吧 1152 | if (variableNameDic.Count == 0) 1153 | { 1154 | BuildStatementCode(); 1155 | } 1156 | 1157 | BindingFlags flags = BindingFlags.SetField | BindingFlags.Instance | (IsPublic() ? BindingFlags.Public : BindingFlags.NonPublic); 1158 | foreach (string vName in variableNameDic.Keys) 1159 | { 1160 | if (!string.IsNullOrEmpty(vName)) 1161 | { 1162 | try 1163 | { 1164 | string varNameToShow = vName.Replace("_", ""); 1165 | scriptType.InvokeMember(varNameToShow, flags, null, targetComponent, new object[] { variableNameDic[vName] }, null, null, null); 1166 | } 1167 | catch (System.Exception e) 1168 | { 1169 | Debug.LogWarning(e.Message); 1170 | } 1171 | } 1172 | } 1173 | } 1174 | } 1175 | } -------------------------------------------------------------------------------- /UICodeBuilderWindow.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a2561150df514b847bf2ab0bc9171faa 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yiiip/Unity-UICodeBuilder/1e8adbf62b9c527688ab59fe67530f7f18029cd5/icon.png -------------------------------------------------------------------------------- /icon.png.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 60a3723ec791b104f8069adf94f8f337 3 | TextureImporter: 4 | fileIDToRecycleName: {} 5 | externalObjects: {} 6 | serializedVersion: 7 7 | mipmaps: 8 | mipMapMode: 0 9 | enableMipMap: 0 10 | sRGBTexture: 1 11 | linearTexture: 0 12 | fadeOut: 0 13 | borderMipMap: 0 14 | mipMapsPreserveCoverage: 0 15 | alphaTestReferenceValue: 0.5 16 | mipMapFadeDistanceStart: 1 17 | mipMapFadeDistanceEnd: 3 18 | bumpmap: 19 | convertToNormalMap: 0 20 | externalNormalMap: 0 21 | heightScale: 0.25 22 | normalMapFilter: 0 23 | isReadable: 0 24 | streamingMipmaps: 0 25 | streamingMipmapsPriority: 0 26 | grayScaleToAlpha: 0 27 | generateCubemap: 6 28 | cubemapConvolution: 0 29 | seamlessCubemap: 0 30 | textureFormat: 1 31 | maxTextureSize: 2048 32 | textureSettings: 33 | serializedVersion: 2 34 | filterMode: 2 35 | aniso: -1 36 | mipBias: -100 37 | wrapU: 1 38 | wrapV: 1 39 | wrapW: -1 40 | nPOTScale: 0 41 | lightmap: 0 42 | compressionQuality: 50 43 | spriteMode: 1 44 | spriteExtrude: 1 45 | spriteMeshType: 1 46 | alignment: 0 47 | spritePivot: {x: 0.5, y: 0.5} 48 | spritePixelsToUnits: 100 49 | spriteBorder: {x: 0, y: 0, z: 0, w: 0} 50 | spriteGenerateFallbackPhysicsShape: 1 51 | alphaUsage: 1 52 | alphaIsTransparency: 1 53 | spriteTessellationDetail: -1 54 | textureType: 8 55 | textureShape: 1 56 | singleChannelComponent: 0 57 | maxTextureSizeSet: 0 58 | compressionQualitySet: 0 59 | textureFormatSet: 0 60 | platformSettings: 61 | - serializedVersion: 2 62 | buildTarget: DefaultTexturePlatform 63 | maxTextureSize: 2048 64 | resizeAlgorithm: 0 65 | textureFormat: -1 66 | textureCompression: 0 67 | compressionQuality: 50 68 | crunchedCompression: 0 69 | allowsAlphaSplitting: 0 70 | overridden: 0 71 | androidETC2FallbackOverride: 0 72 | - serializedVersion: 2 73 | buildTarget: Standalone 74 | maxTextureSize: 2048 75 | resizeAlgorithm: 0 76 | textureFormat: -1 77 | textureCompression: 0 78 | compressionQuality: 50 79 | crunchedCompression: 0 80 | allowsAlphaSplitting: 0 81 | overridden: 0 82 | androidETC2FallbackOverride: 0 83 | spriteSheet: 84 | serializedVersion: 2 85 | sprites: [] 86 | outline: [] 87 | physicsShape: [] 88 | bones: [] 89 | spriteID: 90 | vertices: [] 91 | indices: 92 | edges: [] 93 | weights: [] 94 | spritePackingTag: 95 | pSDRemoveMatte: 0 96 | pSDShowRemoveMatteOption: 0 97 | userData: 98 | assetBundleName: 99 | assetBundleVariant: 100 | -------------------------------------------------------------------------------- /screenshots.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f04e12b72e952d049b0698728bcbf869 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /screenshots/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Yiiip/Unity-UICodeBuilder/1e8adbf62b9c527688ab59fe67530f7f18029cd5/screenshots/01.png -------------------------------------------------------------------------------- /screenshots/01.png.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 229fabf2bc1b49d4381c12b091e737aa 3 | TextureImporter: 4 | fileIDToRecycleName: {} 5 | externalObjects: {} 6 | serializedVersion: 7 7 | mipmaps: 8 | mipMapMode: 0 9 | enableMipMap: 1 10 | sRGBTexture: 1 11 | linearTexture: 0 12 | fadeOut: 0 13 | borderMipMap: 0 14 | mipMapsPreserveCoverage: 0 15 | alphaTestReferenceValue: 0.5 16 | mipMapFadeDistanceStart: 1 17 | mipMapFadeDistanceEnd: 3 18 | bumpmap: 19 | convertToNormalMap: 0 20 | externalNormalMap: 0 21 | heightScale: 0.25 22 | normalMapFilter: 0 23 | isReadable: 0 24 | streamingMipmaps: 0 25 | streamingMipmapsPriority: 0 26 | grayScaleToAlpha: 0 27 | generateCubemap: 6 28 | cubemapConvolution: 0 29 | seamlessCubemap: 0 30 | textureFormat: 1 31 | maxTextureSize: 2048 32 | textureSettings: 33 | serializedVersion: 2 34 | filterMode: -1 35 | aniso: -1 36 | mipBias: -100 37 | wrapU: -1 38 | wrapV: -1 39 | wrapW: -1 40 | nPOTScale: 1 41 | lightmap: 0 42 | compressionQuality: 50 43 | spriteMode: 0 44 | spriteExtrude: 1 45 | spriteMeshType: 1 46 | alignment: 0 47 | spritePivot: {x: 0.5, y: 0.5} 48 | spritePixelsToUnits: 100 49 | spriteBorder: {x: 0, y: 0, z: 0, w: 0} 50 | spriteGenerateFallbackPhysicsShape: 1 51 | alphaUsage: 1 52 | alphaIsTransparency: 0 53 | spriteTessellationDetail: -1 54 | textureType: 0 55 | textureShape: 1 56 | singleChannelComponent: 0 57 | maxTextureSizeSet: 0 58 | compressionQualitySet: 0 59 | textureFormatSet: 0 60 | platformSettings: 61 | - serializedVersion: 2 62 | buildTarget: DefaultTexturePlatform 63 | maxTextureSize: 2048 64 | resizeAlgorithm: 0 65 | textureFormat: -1 66 | textureCompression: 1 67 | compressionQuality: 50 68 | crunchedCompression: 0 69 | allowsAlphaSplitting: 0 70 | overridden: 0 71 | androidETC2FallbackOverride: 0 72 | spriteSheet: 73 | serializedVersion: 2 74 | sprites: [] 75 | outline: [] 76 | physicsShape: [] 77 | bones: [] 78 | spriteID: 79 | vertices: [] 80 | indices: 81 | edges: [] 82 | weights: [] 83 | spritePackingTag: 84 | pSDRemoveMatte: 0 85 | pSDShowRemoveMatteOption: 0 86 | userData: 87 | assetBundleName: 88 | assetBundleVariant: 89 | --------------------------------------------------------------------------------