# unity-uielement **Repository Path**: chasing2moro/unity-uielement ## Basic Information - **Project Name**: unity-uielement - **Description**: Unity UIElement(又名UIToolkit)是最新的UI解决方案,本工程基于UIElement做了一个简单UI框架让大家加深对UIElement的印象 或者 基于它修改来开发游戏。 - **Primary Language**: C# - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-04-20 - **Last Updated**: 2025-04-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # unity-uielement #### 介绍 UIElement(又名UIToolkit)是unity最新的UI解决方案,本工程从取材于 https://assetstore.unity.com/packages/essentials/tutorial-projects/dragon-crashers-ui-toolkit-sample-project-231178 (用了它里面的uxml、uss、tss、图片、一部分代码...)来做一个简单的基于UIElement的UI框架。 继续往下阅读之前,你需要对“uxml、uss、tss、UnityEngine.UIElements下的几个重要类” 有一定的了解。 #### 软件架构 ##### 1. 宽屏竖屏切换 1.1. 预览 ![layout_change](./Img/layout_change.gif) 1.2. 关键代码 ```c# public class UIManager : ObjBase { ... private void Update() { _newIsLandScape = CalIfLandScape();//是否横屏 if (_newIsLandScape != _isLandScape) { _isLandScape = _newIsLandScape; foreach (var docmenet in _docmenet2ui.Keys) { docmenet.panelSettings = GetPanelSettings();//最关键的代码 } } } private bool CalIfLandScape() { return Screen.width > Screen.height; } private PanelSettings GetPanelSettings() { return _isLandScape ? landscape : portrait; } ... } ``` ##### 2. 界面 与 子界面 类的关系 ```mermaid classDiagram UIObject <|-- UIBase界面 UIObject <|-- UIWidget子界面 ``` 预览 ![uibase_uiwidget](./Img/uibase_uiwidget.png) 2.1. 打开界面 关键代码 ```c# UIManager.Instance.Show(UIName.MainMenu, UILayerDefine.Bottom); ``` 2.2. 实例化子界面来显示(和界面本质上都是VisualElement,只不过是挂在界面上) 关键代码 ```c# public class UIBase: UIObject //所有界面都继承UIBase { protected T InitWidget(VisualElement root, System.Object arg) where T: UIWidget { ... } } ``` ##### 3. 绑定控件 控件就是我们经常说的 Label、TextField、Button... - 关键代码(使用者不需要关心,这是底层封装的代码,把成员变量引用到界面上的控件) ```c# public class UIObject { private void Bind(System.Object thisObject, VisualElement rootVisualElement) { var thisType = thisObject.GetType(); var fields = thisType.GetFields(); string bindName; foreach (var field in fields) { var attribute = field.GetCustomAttribute(); if(attribute == null) continue; if (string.IsNullOrEmpty(attribute.bindName)) bindName = field.Name; else bindName = attribute.bindName; var queryNode = rootVisualElement.Q(name: bindName); field.SetValue(thisObject, queryNode); } } } ``` - 例子 ```c# public partial class MainMenu : UIBase { [UIAutoBind("menu__home-button")] public Button menuHomeButton; [UIAutoBind]//不传参,就意味着uxml里控件名和成员变量名一样 public VisualElement HomeScreen; [UIAutoBind("menu__button-group")] public VisualElement m_TopElement; [UIAutoBind("options-bar__button")] public Button optionsBarButton; } ``` #### 联系 chasing2moro@qq.com