unity-ui-data-binding

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Unity UI Toolkit Data Binding

Unity UI Toolkit 数据绑定

Connect your game data (Model) to your interface (View) using modern high-performance data binding. This skill leverages Unity's
unity.properties
system to eliminate "Update" loop logic for UI updates.
使用现代高性能数据绑定将游戏数据(Model)与界面(View)关联起来。本技能借助Unity的
unity.properties
系统,消除UI更新所需的“Update”循环逻辑。

Core Features

核心特性

  1. BindableProperty<T>: A wrapper class that uses
    [CreateProperty]
    to expose values to the UI Toolkit binding engine.
  2. MVVM (Model-View-ViewModel): Separates raw game data from UI-formatted data using a ViewModel mediator.
  3. Reactive Synchronization: UI elements update automatically when the underlying property value changes (or is polled by the engine).
  4. C# Based Binding: Set up complex bindings programmatically without relying on the UI Builder's inspector fields.
  1. BindableProperty<T>:一个使用
    [CreateProperty]
    特性向UI Toolkit绑定引擎暴露值的包装类。
  2. MVVM(Model-View-ViewModel):通过ViewModel中介层将原始游戏数据与UI格式化数据分离。
  3. 响应式同步:当底层属性值变化(或由引擎轮询)时,UI元素会自动更新。
  4. 基于C#的绑定:通过编程方式设置复杂绑定,无需依赖UI Builder的检查器字段。

Core Files (Max 3)

核心文件(最多3个)

  • BindableProperty.cs.txt
    : Generic property wrapper for data sources.
  • BindingExample.cs.txt
    : Practical example showing a Coin display and Health bar bound to a ViewModel.
  • BindableProperty.cs.txt
    :用于数据源的泛型属性包装器。
  • BindingExample.cs.txt
    :展示将金币显示和生命值条绑定到ViewModel的实用示例。

Usage

使用方法

1. Define the ViewModel

1. 定义ViewModel

Initialize
BindableProperty
fields that return formatted data from your model.
csharp
public BindableProperty<string> HealthText { get; }
HealthText = BindableProperty<string>.Bind(() => $"HP: {model.hp}/{model.maxHp}");
初始化
BindableProperty
字段,返回从Model获取的格式化数据。
csharp
public BindableProperty<string> HealthText { get; }
HealthText = BindableProperty<string>.Bind(() => $"HP: {model.hp}/{model.maxHp}");

2. Set the Data Source

2. 设置数据源

Assign your ViewModel to the
dataSource
property of your root VisualElement.
csharp
root.dataSource = myViewModel;
将ViewModel分配给根VisualElement的
dataSource
属性。
csharp
root.dataSource = myViewModel;

3. Establish the Binding

3. 建立绑定

Use
SetBinding
on specific elements to link their properties (text, value, style) to paths in the ViewModel.
csharp
label.SetBinding("text", "HealthText.Value");
在特定元素上使用
SetBinding
,将它们的属性(文本、数值、样式)与ViewModel中的路径关联。
csharp
label.SetBinding("text", "HealthText.Value");

Key Principle

核心原则

Always use one-way binding (ToTarget) for displays and two-way binding only for inputs (checkboxes, text fields). This keeps the "Source of Truth" in your Model.
对于显示内容始终使用单向绑定(ToTarget),仅对输入控件(复选框、文本框)使用双向绑定。这样可以确保“唯一数据源”位于Model中。