ui-ugui
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnderstand existing Unity uGUI, make targeted edits, and generate new Canvas-based hierarchies.
When working with ScrollRect/ScrollView, read the reference file:
- — Required hierarchy, setup rules, and common failures
references/scrollview-setup.md
理解现有Unity uGUI,进行针对性编辑,并生成新的基于Canvas的层级结构。
处理ScrollRect/ScrollView时,请阅读参考文件:
- — 必备层级结构、设置规则及常见问题
references/scrollview-setup.md
Scope
适用范围
Determine what the user is asking for:
| Request Type | Action |
|---|---|
| Question about UI | Understand — analyze hierarchy, explain structure |
| Change specific element | Edit — targeted modification only |
| Create new UI | Generate — create new hierarchy |
| Fix/improve existing UI | Edit — modify existing, don't rebuild |
Generate only what is requested:
| Request | Output |
|---|---|
| UI layout | Prefab or scene hierarchy only |
| "with code" / "with logic" / "functional" | Hierarchy + scripts |
These do NOT imply scripts:
- "proper buttons" → well-configured Button components
- "working UI" → valid hierarchy that renders
- "menu screen" → visual layout only
判断用户需求类型:
| 请求类型 | 操作 |
|---|---|
| UI相关问题 | 理解 — 分析层级结构,解释布局逻辑 |
| 修改特定元素 | 编辑 — 仅进行针对性修改 |
| 创建新UI | 生成 — 创建全新层级结构 |
| 修复/优化现有UI | 编辑 — 修改现有内容,不重建 |
仅生成用户请求的内容:
| 请求内容 | 输出结果 |
|---|---|
| UI布局 | 仅预制体或场景层级结构 |
| "带代码" / "带逻辑" / "可交互" | 层级结构 + 脚本 |
以下表述不意味着需要添加脚本:
- "合适的按钮" → 配置完善的Button组件
- "可用的UI" → 可正常渲染的有效层级结构
- "菜单界面" → 仅视觉布局
Critical Rules
核心规则
Namespace disambiguation:
- Always use fully qualified type names when creating or referencing UI components
- , not
UnityEngine.UI.ImageImage - , not
UnityEngine.UI.ButtonButton - Other namespaces in the project can cause ambiguous type errors
Verify before modifying:
- Always check what currently exists before making changes
- Confirm parent objects exist before adding children
- Verify components are present before modifying properties
- Never assume hierarchy state — query it first
Incremental fixes over rebuilds:
- When fixing issues, make targeted corrections
- Never destroy and recreate entire hierarchies to fix problems — destroyed objects cause null reference cascades
- Prefer identifying the specific broken property and fixing only that over rewriting large sections
- When a fix fails, revert the change before trying an alternative approach
One change at a time:
- Make a single change, then verify the result
- Do not batch multiple unrelated modifications
- Be careful not to inadvertently modify or remove adjacent elements when editing a specific one
- If something fails, understand why before trying alternatives
- Avoid "shotgun debugging" with multiple simultaneous changes
Color and visibility:
- Ensure text is readable by default: When choosing colors, ensure text contrasts with its background — but respect intentional low-contrast uses (disabled states, placeholder text, decorative elements)
- Check visibility for new elements: After creating UI elements, verify they have non-zero size and are within parent bounds. Elements intentionally created hidden (for later toggling, animation, etc.) are fine
Specification adherence:
- Honor user specifications exactly: When the user provides pixel dimensions, hex colors, positions, spacing, or other exact values, apply them precisely — do not approximate or substitute
- Minimize unrelated changes: When editing, avoid changing properties the user didn't ask about unless a related adjustment is necessary for the fix to work
命名空间歧义消除:
- 创建或引用UI组件时,始终使用完全限定类型名称
- 使用而非
UnityEngine.UI.ImageImage - 使用而非
UnityEngine.UI.ButtonButton - 项目中的其他命名空间可能导致类型歧义错误
修改前验证:
- 进行修改前,务必检查当前已有内容
- 添加子对象前,确认父对象存在
- 修改属性前,验证组件已存在
- 绝不假设层级状态 — 先查询再操作
优先增量修复而非重建:
- 修复问题时,进行针对性修正
- 绝不通过销毁并重建整个层级结构来修复问题 — 销毁对象会引发空引用连锁反应
- 优先定位特定的错误属性并仅修复该属性,而非重写大量内容
- 修复失败时,先撤销当前更改再尝试其他方案
一次仅做一处修改:
- 完成一处修改后,验证结果
- 不要批量进行多个无关修改
- 编辑特定元素时,注意不要无意中修改或删除相邻元素
- 若出现问题,先理解原因再尝试其他方案
- 避免同时进行多处修改的“霰弹式调试”
颜色与可见性:
- 确保文本默认可读: 选择颜色时,确保文本与背景形成足够对比度 — 但尊重故意设置的低对比度场景(禁用状态、占位文本、装饰元素)
- 检查新元素的可见性: 创建UI元素后,验证其尺寸非零且处于父对象边界内。若为后续切换、动画等需求故意设置隐藏的元素则无需调整
严格遵循规格:
- 完全遵循用户指定的规格: 当用户提供像素尺寸、十六进制颜色、位置、间距或其他精确值时,严格应用这些值 — 不要近似或替代
- 最小化无关修改: 编辑时,除非为了修复问题必须进行相关调整,否则不要更改用户未提及的属性
Conventions
约定规范
Follow project patterns first. Search existing files before applying defaults.
| Type | Convention | Good | Bad |
|---|---|---|---|
| GameObject names | PascalCase | | |
| Prefab paths | Feature folders | | |
优先遵循项目现有模式。应用默认设置前,先搜索现有文件。
| 类型 | 规范 | 正确示例 | 错误示例 |
|---|---|---|---|
| GameObject名称 | PascalCase命名法 | | |
| 预制体路径 | 按功能划分文件夹 | | |
Workflow
工作流程
- Verify state — Check what exists in the scene/hierarchy before any action.
- Analyze — Determine exactly what's needed. No extras.
- Search — Find existing prefabs, canvases, assets. Don't assume paths.
- Follow project patterns — Match folder structure and naming.
- Create or edit — Build structure with proper anchoring, or make targeted edits.
- Confirm result — Verify the change worked before moving on.
- 验证状态 — 执行任何操作前,检查场景/层级结构中的现有内容。
- 分析需求 — 明确所需内容,不添加额外内容。
- 搜索资源 — 查找现有预制体、Canvas、资源。不要假设路径。
- 遵循项目模式 — 匹配文件夹结构和命名规范。
- 创建或编辑 — 构建带有正确锚定的结构,或进行针对性编辑。
- 确认结果 — 继续操作前,验证修改生效。
Canvas Setup
Canvas设置
Every UI needs a Canvas:
Canvas (Screen Space - Overlay or Camera)
├── CanvasScaler (Scale With Screen Size recommended)
├── GraphicRaycaster
└── [UI Content]CanvasScaler settings:
- Default to UI Scale Mode "Scale With Screen Size" unless the project has a specific reason for "Constant Pixel Size" (e.g., pixel-art, fixed-resolution targets)
- Reference Resolution: Match project standards (e.g., 1920x1080)
- When creating a Canvas with Screen Space - Camera, read the camera's reference resolution first
- Match Width Or Height: 0.5 (balanced)
- If an existing Canvas uses "Constant Pixel Size", flag it and ask the user before changing
- Prefer anchors and Layout Groups over absolute pixel positions for layout
每个UI都需要一个Canvas:
Canvas (Screen Space - Overlay or Camera)
├── CanvasScaler (推荐使用Scale With Screen Size)
├── GraphicRaycaster
└── [UI内容]CanvasScaler设置:
- 默认使用UI缩放模式“Scale With Screen Size”,除非项目有特定原因需使用“Constant Pixel Size”(如像素艺术、固定分辨率目标)
- 参考分辨率:匹配项目标准(如1920x1080)
- 创建Screen Space - Camera模式的Canvas时,先读取相机的参考分辨率
- Match Width Or Height:设置为0.5(平衡模式)
- 若现有Canvas使用“Constant Pixel Size”,修改前需标记并询问用户
- 优先使用锚点和Layout Groups而非绝对像素位置进行布局
Layout Components
布局组件
Layout Groups control child sizing:
- When a parent has a Layout Group, it manages child RectTransforms
- Children's anchors and sizeDelta may be overridden by the parent
- Understand whether the parent or child controls size before setting values
Vertical/Horizontal Layout Groups:
- Control Child Size: determines if parent sets child dimensions
- Child Force Expand: determines if children stretch to fill space
- If Control Child Size is off, children must have explicit sizes
Avoiding layout conflicts:
- Do not manually set child anchors/size when parent controls them
- Do not add Layout Group to an element that should have fixed size
- Nested Layout Groups require careful configuration of each level
- When layout is wrong, check parent settings before modifying child
- ContentSizeFitter on the same object as a Layout Group that has Control Child Size enabled = conflict
- ContentSizeFitter on a child whose parent has Control Child Size enabled = ContentSizeFitter is overridden (wasted)
- When using ContentSizeFitter with a Layout Group parent, disable Control Child Size on the parent for the relevant axis
- Common pattern: ScrollView Content should have ContentSizeFitter + VerticalLayoutGroup where VLG controls children but ContentSizeFitter sizes the Content itself
Grid Layout Group:
- For inventory grids, card layouts
- Cell Size must be set explicitly — children are sized to match
- Constraint controls row/column limits
Content Size Fitter:
- Horizontal/Vertical Fit: Preferred Size
- Use on containers that should size to their content
- Requires a layout element or text component to provide preferred size
Layout Groups控制子对象尺寸:
- 当父对象带有Layout Groups时,它会管理子对象的RectTransform
- 子对象的锚点和sizeDelta可能会被父对象覆盖
- 设置值前,需明确是父对象还是子对象控制尺寸
Vertical/Horizontal Layout Groups:
- Control Child Size:决定父对象是否设置子对象的尺寸
- Child Force Expand:决定子对象是否拉伸以填充空间
- 若Control Child Size关闭,子对象必须设置明确尺寸
避免布局冲突:
- 父对象控制尺寸时,不要手动设置子对象的锚点/尺寸
- 不要为应固定尺寸的元素添加Layout Group
- 嵌套Layout Groups需要仔细配置每一层级
- 布局出现问题时,先检查父对象设置再修改子对象
- 同一对象上同时启用ContentSizeFitter和带有Control Child Size的Layout Group = 冲突
- 父对象启用Control Child Size时,子对象上的ContentSizeFitter会被覆盖(无意义)
- 父对象为Layout Group时,若要使用ContentSizeFitter,需关闭父对象对应轴的Control Child Size
- 常见模式:ScrollView的Content应同时包含ContentSizeFitter + VerticalLayoutGroup,其中VLG控制子对象,ContentSizeFitter控制Content自身尺寸
Grid Layout Group:
- 用于 inventory 网格、卡片布局
- 必须明确设置Cell Size — 子对象会匹配该尺寸
- Constraint控制行/列限制
Content Size Fitter:
- Horizontal/Vertical Fit:设置为Preferred Size
- 用于需要根据内容自动调整尺寸的容器
- 需要布局元素或文本组件提供首选尺寸
RectTransform Anchoring
RectTransform锚定
Elements must have non-zero size to be visible:
- Set explicit width/height via sizeDelta, or
- Use stretch anchors with proper offsets, or
- Let a parent Layout Group control size (with Control Child Size enabled)
Anchor configuration order:
- Set anchor preset first (corner, edge, or stretch)
- Then set position/offset values
- Verify the resulting size is non-zero
Common patterns:
- Stretch anchors — for responsive elements that fill available space
- Corner anchors — for fixed-position, fixed-size elements
- Edge anchors — for elements that stretch in one direction only
Positioning from natural language descriptions:
When the user describes a position (e.g., "top right", "bottom bar", "left side"):
- Determine if it's a corner (fixed point), an edge (stretch along one axis), or fill (stretch both axes)
- Set anchor min and anchor max — for corners these are the same point; for edges/fill they span a range
- Set pivot to match the anchor point — pivot must align with where the element is anchored, not left at the default (0.5, 0.5). A "top right" element needs pivot at the top-right corner; a "top bar" needs pivot at the top edge center
- Set position/offset values after anchors and pivot are configured
Visibility checklist:
- Width and height are both greater than zero
- Element is within parent bounds
- Element is not obscured by siblings (check hierarchy order)
- Image component has a sprite or color with alpha > 0
元素必须具备非零尺寸才能可见:
- 通过sizeDelta设置明确的宽/高,或
- 使用带有适当偏移量的拉伸锚点,或
- 让父Layout Group控制尺寸(启用Control Child Size)
锚点配置顺序:
- 先设置锚点预设(角、边或拉伸)
- 然后设置位置/偏移值
- 验证最终尺寸非零
常见模式:
- 拉伸锚点 — 用于响应式元素,填充可用空间
- 角锚点 — 用于固定位置、固定尺寸的元素
- 边锚点 — 用于仅在单一方向拉伸的元素
根据自然语言描述定位:
当用户描述位置(如“右上角”、“底部栏”、“左侧”)时:
- 判断是角(固定点)、边(沿单一轴拉伸)还是填充(沿双轴拉伸)
- 设置anchor min和anchor max — 角锚点的两个值相同;边/填充锚点的两个值为一个范围
- 设置枢轴以匹配锚点位置 — 枢轴必须与元素的锚定位置对齐,不要保留默认值(0.5, 0.5)。“右上角”元素的枢轴需设置在右上角;“顶部栏”的枢轴需设置在顶部边缘中心
- 配置完锚点和枢轴后,再设置位置/偏移值
可见性检查清单:
- 宽度和高度均大于零
- 元素处于父对象边界内
- 元素未被同级对象遮挡(检查层级顺序)
- Image组件带有精灵或alpha>0的颜色
Common Components
常用组件
| Component | Use Case |
|---|---|
| Backgrounds, icons |
| Render textures, videos |
| All text (use TextMeshPro) |
| Clickable elements |
| Checkboxes, radio buttons |
| Value ranges |
| Scrollable content |
| Text input |
| 组件 | 使用场景 |
|---|---|
| 背景、图标 |
| 渲染纹理、视频 |
| 所有文本(使用TextMeshPro) |
| 可点击元素 |
| 复选框、单选按钮 |
| 值范围调节 |
| 可滚动内容 |
| 文本输入 |
Best Practices
最佳实践
- Use TextMeshPro for all text (not legacy Text)
- WorldSpace UI that have text should also use Text Mesh Pro, be sure to review the project and import the TMP essentials if they are not present in the project
- If the TextMeshPro Essentials were imported be sure to close the TMP Importer Windows and the Import Unity Package Window once the assets are imported
- Organize hierarchy logically (Header, Content, Footer)
- Use Layout Groups instead of manual positioning where possible
- Set Raycast Target = false on non-interactive images
- Use sprite atlases for performance
Never use , unless the user asks for an interactive TMP Essentials installation. It opens a modal dialog that blocks whatever invoked it until a human dismisses it.
EditorApplication.ExecuteMenuItem("Window/TextMeshPro/Import TMP Essential Resources")Do not use for TMP resources, instead is the canonical non-interactive API.
AssetDatabase.ImportPackage()TMP_PackageResourceImporter.ImportResources()- 所有文本使用TextMeshPro(而非旧版Text)
- 带有文本的WorldSpace UI也应使用Text Mesh Pro,若项目中未包含TMP基础资源,需先查看项目并导入
- 若已导入TextMeshPro基础资源,导入完成后务必关闭TMP导入窗口和Unity包导入窗口
- 逻辑化组织层级结构(Header、Content、Footer)
- 尽可能使用Layout Groups而非手动定位
- 非交互式Image组件设置Raycast Target = false
- 使用精灵图集提升性能
切勿使用 ,除非用户明确要求交互式导入TMP基础资源。该方法会打开模态对话框,阻塞调用进程直到人工关闭。
EditorApplication.ExecuteMenuItem("Window/TextMeshPro/Import TMP Essential Resources")不要使用 导入TMP资源,推荐使用这一标准非交互式API。
AssetDatabase.ImportPackage()TMP_PackageResourceImporter.ImportResources()Interaction Readiness
交互就绪检查
Before completing any UI that contains interactive elements, verify:
- EventSystem must exist in the scene (exactly one)
- GraphicRaycaster must be on the Canvas
- Raycast Target = true on interactive elements (and false on non-interactive ones to avoid blocking)
- Button.onClick should be wired (via inspector or script) — only when scripts or logic were requested
If the first three are missing, interactive elements will exist visually but fail silently.
完成包含交互元素的UI前,需验证:
- 场景中必须存在EventSystem(且仅一个)
- Canvas上必须带有GraphicRaycaster
- 交互式元素的Raycast Target = true(非交互式元素设置为false以避免阻塞)
- Button.onClick需已绑定(通过检视面板或脚本) — 仅当用户要求添加脚本或逻辑时才需配置
若缺少前三项,交互元素会正常显示但无法响应操作。
Understanding
理解现有UI
When the user asks questions about existing UI:
Read the hierarchy first. Don't assume — always inspect the scene or prefab before answering.
Analyze structure:
- Identify the Canvas and its render mode
- Map the parent-child relationships
- Identify which Layout Groups control which children
- Check RectTransform anchor configurations
Answer questions about:
- "What does this button do?" → Explain component, hierarchy position, event wiring
- "How is this laid out?" → Describe Layout Groups, anchoring, hierarchy
- "Why is this invisible?" → Check size, anchors, parent bounds, component state
- "What controls this element's size?" → Trace Layout Group settings or anchors
当用户询问现有UI相关问题时:
先读取层级结构。不要假设 — 回答前务必检查场景或预制体。
分析结构:
- 识别Canvas及其渲染模式
- 梳理父-子关系
- 确定哪些Layout Groups控制哪些子对象
- 检查RectTransform锚点配置
可回答的问题类型:
- “这个按钮有什么作用?” → 解释组件、层级位置、事件绑定
- “这个布局是如何实现的?” → 描述Layout Groups、锚定方式、层级结构
- “为什么这个元素不可见?” → 检查尺寸、锚点、父对象边界、组件状态
- “什么控制这个元素的尺寸?” → 追溯Layout Group设置或锚点配置
Editing
编辑现有UI
For targeted changes to existing UI:
Read before editing. Always inspect the current state first.
Edit workflow:
- Verify the target object exists
- Identify the specific property or component to change
- Make the minimal change required
- Verify the result before proceeding
Never destroy to fix:
- Destroying objects cascades to null references elsewhere
- Fix properties in place rather than recreating
- If an element must be removed, update all references first
对现有UI进行针对性修改时:
编辑前先读取内容。务必先检查当前状态。
编辑工作流程:
- 验证目标对象存在
- 确定需修改的特定属性或组件
- 进行最小必要修改
- 继续操作前验证结果
绝不通过销毁来修复:
- 销毁对象会引发其他地方的空引用
- 优先在原位置修复属性而非重新创建
- 若必须移除元素,先更新所有引用
C# (Only When Requested)
C#(仅在用户要求时使用)
- Use fully qualified UI types to avoid namespace conflicts
- Use for inspector references
[SerializeField] - Cache component references in Awake()
- Use events/delegates for button callbacks
- Place scripts in same folder as prefabs (follow project patterns)
Component references:
- Verify referenced objects exist before accessing them
- Handle cases where serialized references may be null
- When wiring up references, confirm the target component is present
- 使用完全限定的UI类型以避免命名空间冲突
- 使用暴露检视面板引用
[SerializeField] - 在Awake()中缓存组件引用
- 使用事件/委托处理按钮回调
- 脚本放置在与预制体相同的文件夹中(遵循项目模式)
组件引用:
- 访问前验证引用对象存在
- 处理序列化引用可能为空的情况
- 绑定引用时,确认目标组件已存在
Error Recovery
错误恢复
When something goes wrong:
Stop and diagnose:
- Identify the exact error or symptom
- Determine the root cause before attempting fixes
- Do not make speculative changes
Fix incrementally:
- Address one issue at a time
- Verify each fix before moving to the next
- Keep track of what was changed
Avoid destructive patterns:
- "Start fresh" strategies destroy working elements along with broken ones
- Rebuilding entire hierarchies creates more problems than it solves
- Prefer surgical fixes to wholesale replacements
When stuck:
- Re-verify the current state of the hierarchy
- Check if previous changes were actually applied
- Consider if the approach itself is wrong rather than the implementation
出现问题时:
停止操作并诊断:
- 明确具体错误或症状
- 尝试修复前先确定根本原因
- 不要进行推测性修改
增量修复:
- 一次解决一个问题
- 完成一个修复后再进行下一个
- 记录所有修改内容
避免破坏性操作:
- “重新开始”策略会同时销毁正常和异常元素
- 重建整个层级结构会引发更多问题
- 优先进行精准修复而非全面替换
遇到瓶颈时:
- 重新验证层级结构的当前状态
- 检查之前的修改是否已实际应用
- 考虑是否是方案本身存在问题而非实现错误",