unity-ui-data-binding
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnity 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 system to eliminate "Update" loop logic for UI updates.
unity.properties使用现代高性能数据绑定将游戏数据(Model)与界面(View)关联起来。本技能借助Unity的系统,消除UI更新所需的“Update”循环逻辑。
unity.propertiesCore Features
核心特性
- BindableProperty<T>: A wrapper class that uses to expose values to the UI Toolkit binding engine.
[CreateProperty] - MVVM (Model-View-ViewModel): Separates raw game data from UI-formatted data using a ViewModel mediator.
- Reactive Synchronization: UI elements update automatically when the underlying property value changes (or is polled by the engine).
- C# Based Binding: Set up complex bindings programmatically without relying on the UI Builder's inspector fields.
- BindableProperty<T>:一个使用特性向UI Toolkit绑定引擎暴露值的包装类。
[CreateProperty] - MVVM(Model-View-ViewModel):通过ViewModel中介层将原始游戏数据与UI格式化数据分离。
- 响应式同步:当底层属性值变化(或由引擎轮询)时,UI元素会自动更新。
- 基于C#的绑定:通过编程方式设置复杂绑定,无需依赖UI Builder的检查器字段。
Core Files (Max 3)
核心文件(最多3个)
- : Generic property wrapper for data sources.
BindableProperty.cs.txt - : Practical example showing a Coin display and Health bar bound to a ViewModel.
BindingExample.cs.txt
- :用于数据源的泛型属性包装器。
BindableProperty.cs.txt - :展示将金币显示和生命值条绑定到ViewModel的实用示例。
BindingExample.cs.txt
Usage
使用方法
1. Define the ViewModel
1. 定义ViewModel
Initialize fields that return formatted data from your model.
BindablePropertycsharp
public BindableProperty<string> HealthText { get; }
HealthText = BindableProperty<string>.Bind(() => $"HP: {model.hp}/{model.maxHp}");初始化字段,返回从Model获取的格式化数据。
BindablePropertycsharp
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 property of your root VisualElement.
dataSourcecsharp
root.dataSource = myViewModel;将ViewModel分配给根VisualElement的属性。
dataSourcecsharp
root.dataSource = myViewModel;3. Establish the Binding
3. 建立绑定
Use on specific elements to link their properties (text, value, style) to paths in the ViewModel.
SetBindingcsharp
label.SetBinding("text", "HealthText.Value");在特定元素上使用,将它们的属性(文本、数值、样式)与ViewModel中的路径关联。
SetBindingcsharp
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中。