跳转至

Unity 6.3 — UI Module Reference

最后验证: 2026-02-13
Knowledge Gap: Unity 6 UI Toolkit 已可投放至运行时 UI(生产就绪)


概述

Unity 6 UI 系统:

  • UI Toolkit(推荐):现代、高性能、类 HTML/CSS(在 Unity 6 中已生产就绪)
  • UGUI(Canvas):旧版系统,仍受支持,但不推荐用于新项目
  • IMGUI:仅限编辑器,已弃用于运行时 UI

UI Toolkit(现代 UI)

设置 UI Document

  1. 创建 UXML(UI 结构):
  2. Assets > Create > UI Toolkit > UI Document
  3. 创建 USS(样式):
  4. Assets > Create > UI Toolkit > StyleSheet
  5. 添加到场景:
  6. GameObject > UI Toolkit > UI Document
  7. 将 UXML 分配给 UIDocument > Source Asset

UXML(UI 结构)

<!-- MainMenu.uxml -->
<ui:UXML xmlns:ui="UnityEngine.UIElements">
    <ui:VisualElement class="container">
        <ui:Label text="Main Menu" class="title" />
        <ui:Button name="play-button" text="Play" />
        <ui:Button name="settings-button" text="Settings" />
        <ui:Button name="quit-button" text="Quit" />
    </ui:VisualElement>
</ui:UXML>

USS(样式)

/* MainMenu.uss */
.container {
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: rgb(30, 30, 30);
}

.title {
    font-size: 48px;
    color: white;
    margin-bottom: 20px;
}

Button {
    width: 200px;
    height: 50px;
    margin: 10px;
    font-size: 24px;
}

Button:hover {
    background-color: rgb(100, 150, 200);
}

C# 脚本(UI Toolkit)

using UnityEngine;
using UnityEngine.UIElements;

public class MainMenu : MonoBehaviour {
    void OnEnable() {
        var root = GetComponent<UIDocument>().rootVisualElement;

        // Query elements by name
        var playButton = root.Q<Button>("play-button");
        var settingsButton = root.Q<Button>("settings-button");
        var quitButton = root.Q<Button>("quit-button");

        // Register callbacks
        playButton.clicked += OnPlayClicked;
        settingsButton.clicked += OnSettingsClicked;
        quitButton.clicked += Application.Quit;
    }

    void OnPlayClicked() {
        Debug.Log("Play clicked");
        // Load game scene
    }

    void OnSettingsClicked() {
        Debug.Log("Settings clicked");
        // Open settings menu
    }
}

常用 UI 元素

// Label (text display)
var label = root.Q<Label>("score-label");
label.text = "Score: 100";

// Button
var button = root.Q<Button>("submit-button");
button.clicked += OnSubmit;

// TextField (text input)
var textField = root.Q<TextField>("name-input");
string playerName = textField.value;

// Toggle (checkbox)
var toggle = root.Q<Toggle>("music-toggle");
bool isMusicEnabled = toggle.value;

// Slider
var slider = root.Q<Slider>("volume-slider");
float volume = slider.value; // 0-1

// DropdownField (dropdown menu)
var dropdown = root.Q<DropdownField>("difficulty-dropdown");
dropdown.choices = new List<string> { "Easy", "Normal", "Hard" };
dropdown.value = "Normal";

动态创建 UI(不使用 UXML)

void CreateUI() {
    var root = GetComponent<UIDocument>().rootVisualElement;

    // Create elements
    var container = new VisualElement();
    container.AddToClassList("container");

    var label = new Label("Hello, UI Toolkit!");
    var button = new Button(() => Debug.Log("Clicked")) { text = "Click Me" };

    container.Add(label);
    container.Add(button);
    root.Add(container);
}

USS Flexbox 布局

/* Horizontal layout */
.horizontal {
    flex-direction: row;
}

/* Vertical layout (default) */
.vertical {
    flex-direction: column;
}

/* Center children */
.centered {
    align-items: center;
    justify-content: center;
}

/* Spacing */
.spaced {
    justify-content: space-between;
}

UGUI(旧版 Canvas UI)

基本设置(在 Unity 6 中仍可使用)

// GameObject > UI > Canvas (creates Canvas, EventSystem)

// UI Elements:
// - Text (use TextMeshPro instead)
// - Button
// - Image
// - Slider
// - Toggle
// - InputField

UGUI 脚本

using UnityEngine;
using UnityEngine.UI;
using TMPro; // TextMeshPro

public class LegacyUI : MonoBehaviour {
    public TextMeshProUGUI scoreText;
    public Button playButton;
    public Slider volumeSlider;

    void Start() {
        // Update text
        scoreText.text = "Score: 100";

        // Button click
        playButton.onClick.AddListener(OnPlayClicked);

        // Slider value changed
        volumeSlider.onValueChanged.AddListener(OnVolumeChanged);
    }

    void OnPlayClicked() {
        Debug.Log("Play clicked");
    }

    void OnVolumeChanged(float value) {
        AudioListener.volume = value;
    }
}

TextMeshPro(更好的文本渲染)

// Install: Window > TextMeshPro > Import TMP Essential Resources

// Use TMP_Text instead of Unity's Text component
using TMPro;

public TextMeshProUGUI tmpText;
tmpText.text = "High Quality Text";
tmpText.fontSize = 24;
tmpText.color = Color.white;

Canvas 设置(UGUI)

渲染模式

// Screen Space - Overlay: UI rendered on top of everything (no camera needed)
// Screen Space - Camera: UI rendered by specific camera (allows effects)
// World Space: UI in 3D world (e.g., floating health bars)

Canvas Scaler(响应式 UI)

// UI Scale Mode:
// - Constant Pixel Size: UI elements have fixed pixel size
// - Scale With Screen Size: UI scales based on reference resolution (RECOMMENDED)
// - Constant Physical Size: UI elements have fixed physical size (cm)

// Example: Scale With Screen Size
// Reference Resolution: 1920x1080
// Screen Match Mode: Match Width Or Height (0.5 = balanced)

布局组(UGUI)

水平布局组

// Auto-arranges children horizontally
// Add: GameObject > Add Component > Horizontal Layout Group

垂直布局组

// Auto-arranges children vertically

网格布局组

// Arranges children in a grid

性能(UI Toolkit 与 UGUI 对比)

UI Toolkit 优势

  • ✅ 渲染更快(保留模式)
  • ✅ 更适合包含大量元素的复杂 UI
  • ✅ 样式更简单(类似 CSS)
  • ✅ 更适合动态 UI

UGUI 优势

  • ✅ 更成熟,文档广泛
  • ✅ 与 Unity Editor 集成更好
  • ✅ 对初学者更友好

常见模式

生命条(UI Toolkit)

var healthBar = root.Q<VisualElement>("health-bar");
healthBar.style.width = new StyleLength(new Length(healthPercent, LengthUnit.Percent));

生命条(UGUI)

public Image healthBarImage;

void UpdateHealth(float percent) {
    healthBarImage.fillAmount = percent; // 0-1
}

淡入/淡出(UI Toolkit)

IEnumerator FadeIn(VisualElement element, float duration) {
    float elapsed = 0f;
    while (elapsed < duration) {
        elapsed += Time.deltaTime;
        element.style.opacity = Mathf.Lerp(0f, 1f, elapsed / duration);
        yield return null;
    }
}

调试

UI Toolkit 调试器

  • Window > UI Toolkit > Debugger
  • 检查元素层级、样式和布局

UGUI 事件系统调试器

  • 在 Hierarchy 中选择 EventSystem
  • Inspector 会显示当前激活的输入模块和射线检测信息

参考来源

  • https://docs.unity3d.com/6000.0/Documentation/Manual/UIElements.html
  • https://docs.unity3d.com/Packages/com.unity.ui@2.0/manual/index.html
  • https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/index.html

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 cl/Claude-Code-Game-Studios