Version: 2023.2
언어: 한국어
Bind to a list without ListView
Bind a custom control to custom data type

Bind a custom control

Version: 2021.3+

This example demonstrates how to bind a custom control to a native Unity type.

개요 예시

The example creates a custom control that displays a 2D image. It uses the custom control in a custom Editor for a new asset type, and it binds the custom control to a field in an asset of the new type.

You can find the completed files that this example creates in this GitHub repository.

선행 조건

This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:

Create a serialized object

Create a serialized object that contains a Texture2D.

  1. Create a Unity project with any template.
  2. In the Project window, create a folder named bind-custom-control to store the files.
  3. Create a C# script named TextureAsset.cs and replace its contents with the following:

[!code-cs]

Create and style a custom control

Create a custom control with C# that represents a reference to a 2D texture asset, and style it with USS.

  1. In that folder, create a folder named Editor.
  2. In the Editor folder, create a C# script named TexturePreviewElement.cs.
  3. Replace the contents of TexturePreviewElement.cs with the following:

[!code-cs]

  1. In the Editor folder, create a folder named Resources.
  2. In the Resources folder, create a StyleSheet named texture_preview_element.uss and replace its contents with the following:

[!code-css]

Create the Inspector UI

Create the Inspector UI, and bind the custom control to the Texture2D object.

  1. In the Editor folder, create a C# script named TextureAssetEditor.cs and replace its contents with the following:

[!code-cs]

Set the binding with UXML

Create a UXML file with a TexturePreviewElement, and set the binding-path property to texture. This binds the TexturePreviewElement to TextureAsset.texture.

  1. In the Editor folder, create a UI Document named texture_asset_editor.uxml and replace its contents with the following:

[!code-xml]

  1. In the Project window, select TextureAssetEditor.cs.
  2. Drag texture_asset_editor.uxml to Visual Tree in the Inspector.

Test the binding

  1. From the menu, select Assets > Create > UIToolkitExamples > TextureAsset. This creates an instance of a TextureAsset.
  2. Select the new TextureAsset object. In the Inspector, you can see the Texture Preview Element. If you put a texture asset reference into the field, you can see a preview above the field. If you change the asset reference in the Texture Preview Element in the UI, the TextureAsset.texture changes.

추가 리소스

Bind to a list without ListView
Bind a custom control to custom data type
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961