Version: Unity 6.0 (6000.0)
언어 : 한국어
런타임 바인딩 시작
런타임 바인딩을 위한 데이터 소스 정의

C# 스크립트에서 런타임 바인딩 생성

C#에서 시각적 요소의 프로퍼티를 데이터 소스에 바인딩하려면 DataBinding의 인스턴스를 생성합니다. 이 바인딩 타입을 사용하면 바인딩 인스턴스에서 직접 dataSourcedataSourcePath를 정의할 수 있습니다.

기본 워크플로

C#에서 런타임 바인딩을 생성하려면 다음 단계를 따르십시오.

  1. 바인딩을 생성합니다. 바인딩은 고유한 ID를 통해 시각적 요소에 생성, 등록 또는 등록 취소할 수 있는 오브젝트입니다.
  2. 바인딩 오브젝트의 데이터 소스 경로 및 데이터 소스를 정의합니다. 데이터 소스는 바인딩하려는 프로퍼티가 포함된 오브젝트입니다. 데이터 소스 경로는 데이터 소스에서 바인딩하려는 프로퍼티까지의 상대 경로입니다.
  3. 바인딩 오브젝트에 대한 바인딩 모드를 정의하고 트리거를 업데이트합니다. 바인딩 모드는 변경 사항이 데이터 소스와__ UI__(사용자 인터페이스) 사용자가 애플리케이션과 상호 작용하도록 해 줍니다. Unity는 현재 3개의 UI 시스템을 지원합니다. 자세한 정보
    See in Glossary
    간에 복제되는 방식을 정의합니다. 업데이트 트리거는 바인딩 오브젝트를 업데이트할 시기를 정의합니다.
  4. 바인딩 오브젝트를 시각적 요소에 등록합니다.
  5. 필요한 경우 타입 컨버터를 추가하여 데이터 소스와 UI 간의 데이터 타입을 전환합니다.

다음 예시에서는 바인딩 오브젝트를 생성하여 시각적 요소에 등록합니다.

var dataSource = ScriptableObject.CreateInstance<ExampleObject>();

var root = new VisualElement
{
    name = "root",
    dataSource = dataSource
};

var vector3Field = new Vector3Field("Vec3 Field");

vector3Field.SetBinding("label", new DataBinding
{
    dataSourcePath = new PropertyPath(nameof(ExampleObject.vector3Label)),
    bindingMode = BindingMode.ToTarget
});

vector3Field.SetBinding("value", new DataBinding
{
    dataSourcePath = new PropertyPath(nameof(ExampleObject.vector3Value))
});

root.Add(vector3Field);

var floatField = new FloatField("Float Field") { value = 42.2f };

floatField.SetBinding("value", new DataBinding
{
    dataSourcePath = new PropertyPath(nameof(ExampleObject.sumOfVector3Properties))
});

root.Add(floatField);

var label = new Label("Label")
{
    dataSourcePath = new PropertyPath(nameof(ExampleObject.dangerLevel))
};

// Here, we do not need to set the dataSourcePath because we will only use two bindings and they will use the same path,
// so we set the dataSourcePath on the Label directly instead.
var binding = new DataBinding
{
    bindingMode = BindingMode.ToTarget
};

// Add a custom float -> string converter
binding.sourceToUiConverters.AddConverter((ref float v) => 
{
    return v switch
    {
        >= 0 and < 1.0f/3.0f => "Danger",
        >= 1.0f/3.0f and < 2.0f/3.0f => "Neutral",
        _ => "Good"
    };
});

// Add a custom float -> StyleColor
binding.sourceToUiConverters.AddConverter((ref float v) => new StyleColor(Color.Lerp(Color.red, Color.green, v)));

// Since the binding is targeting the same data source property, we can re-use the same instance.
label.SetBinding("text", binding);
label.SetBinding("style.backgroundColor", binding);

root.Add(label);

이는 다음 UXML과 동일합니다.

<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" 
editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    <ui:VisualElement data-source="ExampleObject.asset" name="VisualElement" >
        <ui:Vector3Field label="Vec3 Field">
            <Bindings>
                <ui:DataBinding property="label" data-source-path="vector3Label" binding-mode="ToSource" />
                <ui:DataBinding property="value" data-source-path="vector3Value" />
            </Bindings>
        </ui:Vector3Field>
        <ui:FloatField label="Float Field" value="42.2">
            <Bindings>
                <ui:DataBinding property="value" data-source-path="sumOfVector3Properties" binding-mode="ToTarget" />
            </Bindings>
        </ui:FloatField>
        <ui:Label text="Label" data-source-path="dangerLevel">
            <Bindings>
                <ui:DataBinding property="text" binding-mode="ToTarget" source-to-ui-converters="Value To Progress" />
                <ui:DataBinding property="style.backgroundColor" binding-mode="ToTarget" source-to-ui-converters="Value To Progress" />
            </Bindings>
    </ui:Label>
    </ui:VisualElement>
</ui:UXML>

바인딩 오브젝트 등록 및 등록 취소

다음 메서드를 사용하여 바인딩 오브젝트를 관리할 수 있습니다.

변경 사항 보고

다른 데이터 소스와 동일한 방식으로 바인딩 가능한 프로퍼티를 생성할 수 있습니다. 즉, VisualElement 타입을 데이터 소스로 사용할 수도 있습니다. VisualElement 타입과 다른 데이터 소스의 주요 차이점은 VisualElement 타입이 빌트인 버전 관리 기능과 함께 제공되는 것입니다. 변경 사항을 전파하려면 VisualElement 타입의 빌트인 버전 관리 기능을 사용해야 합니다.

변경 사항을 보고하려면 NotifyPropertyChanged 메서드를 호출합니다. 이 메서드는 변경된 프로퍼티를 식별하는 BindingId를 사용합니다. 다음 예시에서는 변경 사항을 리포트하는 방법을 보여 줍니다.

// Creates a static readonly BindingId that is unique to this type. This is used to identify the property. 
public static readonly BindingId intValueProperty = nameof(intValue);

private int m_IntValue;

[CreateProperty]
public int intValue
{
    get => m_IntValue;
    set
    {
        if (m_IntValue == value)
            return;
        m_IntValue = value;
        
        // This instructs the binding system that a change occured.
        NotifyPropertyChanged(intValueProperty);
    }
}

베스트 프랙티스

다음 팁과 베스트 프랙티스를 따라 성능을 최적화하십시오.

  • 올바른 바인딩 ID 사용: 바인딩 시스템은 바인딩 ID를 사용하여 바인딩 오브젝트와 요소의 타겟 프로퍼티를 식별합니다. 바인딩 ID는 요소의 타겟 프로퍼티여야 합니다. 예를 들어, Vector3Fieldvalue 프로퍼티에 바인딩하려면 바인딩 ID가 Vector3Field.valueProperty여야 합니다.
  • 바인딩을 통한 내부 데이터 업데이트 금지: 바인딩을 사용하여 시각적 요소의 내부 데이터를 업데이트하지 마십시오. 예를 들어 바인딩을 사용하여 Vector3Fieldx, y, z 하위 요소를 동기화하지 마십시오. 대신 바인딩을 사용하여 Vector3Fieldvalue 프로퍼티를 데이터 소스의 Vector3 프로퍼티와 동기화합니다.

알려진 제한 사항

UI 툴킷은 element.styleelement.resolvedStyle의 변경 사항을 보고하지 않습니다. 따라서 바인딩 인스턴스를 사용하여 요소의 확인된 스타일을 타게팅할 수 있지만 변경 사항은 추적할 수 없습니다.

추가 리소스

런타임 바인딩 시작
런타임 바인딩을 위한 데이터 소스 정의
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961