Bindings
The purpose of bindings is to synchronize properties within objects to the visible UI (User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary . A binding refers to the link between the property and the visual control that modifies it.
Binding is done between an object and any UIElement that either derives from BindableElement or implements the IBindable interface.
From the UnityEditor.UIElements namespace:
Base Class:
- BaseCompositeField
- BasePopupField
- CompoundFields
- TextValueField
Controls:
- InspectorElement
- ProgressBar
- BoundsField
- BoundsIntField
- ColorField
- CurveField
- DoubleField
- EnumField
- FloatField
- GradientField
- IntegerField
- LayerField
- LayerMaskField
- LongField
- MaskField
- ObjectField
- PopupField
- RectField
- RectIntField
- TagField
- Vector2Field
- Vector2IntField
- Vector3Field
- Vector3IntField
- Vector4Field
From the UnityEngine.UIElements namespace:
Base Class
- BaseField
- BaseSlider
- TextInputBaseField
- TemplateContainer
Controls
- Foldout
- MinMaxSlider
- Slider
- SliderInt
- TextField
- Toggle
Binding is done by following these steps while using a Control from one of the namespaces listed above.
- In the Control, specify the bindingPath from the IBindable interface so the UI knows which property to bind. You can do this in C# or in UXML. An example of each is provided later in this topic.
- Create a SerializedObject for the object being bound.
- Bind this object to the Control or one of its parents.
Binding with C#
The following code snippet shows how to create a binding with C# code. To use this snippet, save this example as a C# file in an editor folder, in your project. Name the C# file SimpleBindingExample.cs .
The contents of SimpleBindingExample.cs :
In Unity, select Window > UIElementsExamples > Simple Binding Example. You can use this window to select any GameObject in your scene and modify its name with the TextField shown.
Binding with UXML
This section shows how to use binding through the UXML hierarchy set-up.
In UXML, the attribute binding-path is defined in the TextField control A TextField control displays a non-interactive piece of text to the user, such as a caption, label for other GUI controls, or instruction. More info
See in Glossary . This is what binds the control to the effective property of the object.
The contents of SimpleBindingExample.uxml :
The contents of SimpleBindingExample.cs :
Using bindings within InspectorElement
An InspectorElement is the UIElement counterpart of an inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary that is meant a specific type of Unity object. Using an InspectorElement to inspect objects gives the following advantages :
- Creates the UI.
- Automatically binds objects and the UI.
Another simple binding example, found under Assets/Editor/SimpleBindingExample.cs , provides a usage example and an overview of the process.
The contents of Assets/Editor/SimpleBindingExample.cs :
This code references the TankScript script and uses the InspectorElement . The TankScript script is an example of a MonoBehaviour assigned to a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary .
The contents of Assets/TankScript.cs :
The InspectorElement is customized with a specific UI. This is done with the TankEditor script. The TankEditor script defines a custom editor for the TankScript type. The TankEditor script also uses a UXML file for the hierarchy and a USS file to style the inspector.
The contents of Assets/Editor/TankEditor.cs :
The contents of Assets/Resources/tank_inspector_uxml.uxml :
The UXML file, tank_inspector_uxml.uxml specifies the binding. Specifically, each binding-path attribute, for each the PropertyFields tag, is set to the property to bind. What element is shown in the UI is based on the type of each bound property.
The contents of Assets/Resources/tank_inspector_styles.uss :
The USS file, tank_inspector_styles.uss , defines the style of each element.
The following table lists the fields supported by the PropertyField. Each field includes its data type.
Связи
Целью привязок является синхронизация свойств внутри объектов с видимым UI (пользовательский интерфейс) Позволяет пользователю взаимодействовать с ваше приложение. Подробнее
См. в Словарь . Привязка относится к связи между свойством и визуальным элементом управления, который его изменяет.
Связывание выполняется между объектом и любым UIElement, который либо является производным от BindableElement, либо реализует интерфейс IBindable.
Из пространства имен UnityEditor.UIElements :
Базовый класс:
- BaseCompositeField
- BasePopupField
- CompoundFields
- TextValueField
Элементы управления:
- InspectorElement
- ProgressBar
- BoundsField
- BoundsIntField
- ColorField
- CurveField
- DoubleField
- EnumField
- FloatField
- GradientField
- IntegerField
- LayerField
- LayerMaskField
- LongField
- MaskField
- ObjectField
- PopupField
- PropertyControl
- RectField
- RectIntField
- TagField
- Vector2Field
- Vector2IntField
- Vector3Field
- Vector3IntField
- Vector4Field
Из пространства имен UnityEngine.UIElements :
Базовый класс
- BaseField
- BaseSlider
- TextInputBaseField
- TemplateContainer
Элементы управления
- Foldout
- MinMaxSlider
- Slider
- SliderInt
- TextField
- Toggle
Привязка выполняется с помощью следующих шагов при использовании элемента управления из одного из перечисленных выше пространств имен.
- В элементе управления укажите bindingPath из интерфейса IBindable, чтобы пользовательский интерфейс знал, какое свойство нужно привязать. Вы можете сделать это в C# или в UXML. Пример каждого приведен ниже в этом разделе.
- Создайте SerializedObject для связываемого объекта.
- Привяжите этот объект к элементу управления или одному из его родителей.
Связывание с C#
В следующем фрагменте кода показано, как создать привязку с помощью кода C#. Чтобы использовать этот фрагмент, сохраните этот пример как файл C# в папке редактора в вашем проекте. Назовите файл C# SimpleBindingExample.cs .
Содержимое файла SimpleBindingExample.cs :
В Unity выберите Окно > UIElementExamples > Простой пример привязки. Вы можете использовать это окно, чтобы выбрать любой игровой объект в вашей сцене и изменить его имя с отображаемым текстовым полем.
Связывание с UXML
В этом разделе показано, как использовать привязку через настройку иерархии UXML.
В UXML атрибут binding-path определяется в элементе управления TextField Элемент управления TextField отображает неинтерактивный фрагмент текста для пользователя, например заголовок, метку для других элементов управления графического интерфейса или инструкцию. Подробнее
См. в Словарь . Это то, что связывает элемент управления с эффективным свойством объекта.
Содержимое файла SimpleBindingExample.uxml :
<UXML xmlns:ui=»UnityEngine.UIElements»> <ui:VisualElement name=»top-element»> <ui:Label name=»top-label» text=»UXML-Defined Simple Binding»/> <ui:TextField name=»GameObjectName» label=»Name» text=»» binding-path=»m_Name»/> </ui:VisualElement> </UXML>
Содержимое файла SimpleBindingExample.cs :
Использование привязок в InspectorElement
InspectorElement — это UIElement-аналог инспектора окна Unity. который отображает информацию о текущем выбранном игровом объекте, активе или настройках проекта, позволяя вам проверять и редактировать значения. Дополнительная информация
Посмотрите в Словарь , что имеется в виду определенный тип объекта Unity. Использование InspectorElement для проверки объектов дает следующие преимущества:
- Создает пользовательский интерфейс.
- Автоматически связывает объекты и пользовательский интерфейс.
Еще один пример простой привязки, который можно найти в разделе Assets/Editor/SimpleBindingExample.cs , содержит пример использования и обзор процесса.
Содержимое файла Assets/Editor/SimpleBindingExample.cs :
Этот код ссылается на скрипт TankScript и использует InspectorElement . Сценарий TankScript является примером MonoBehaviour, назначенного GameObject фундаментальному объект в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь .
InspectorElement настраивается с помощью определенного пользовательского интерфейса. Это делается с помощью скрипта TankEditor . Сценарий TankEditor определяет пользовательский редактор для типа TankScript . Сценарий TankEditor также использует файл UXML для иерархии и файл USS для оформления инспектора.
Содержимое файла Assets/Editor/TankEditor.cs :
Содержимое файла Assets/Resources/tank_Included_uxml.uxml :
<UXML xmlns:ui=»UnityEngine.UIElements» xmlns:ue=»UnityEditor.UIElements»> <ui:VisualElement name=»row» > <ui:Label text=»Tank Script — Custom Inspector» /> <ue:PropertyField binding-path=»tankName» name=»tank-name-field» /> <ue:PropertyField binding-path=»tankSize» name=»tank-size-field» /> </ui:VisualElement> </UXML>
Файл UXML, tank_инспекционный_uxml.uxml определяет привязку. В частности, каждый атрибут binding-path для каждого тега PropertyFields задается свойством для привязки. Какой элемент отображается в пользовательском интерфейсе, зависит от типа каждого связанного свойства.
Содержимое файла Assets/Resources/tank_Included_styles.uss :
Файл USS, tank_Included_styles.uss , определяет стиль каждого элемента.
В следующей таблице перечислены поля, поддерживаемые PropertyField. Каждое поле включает свой тип данных.
Как UI объект прикрепить к gameobject?
1) взять персонажа, пересчитать его координаты в экранные или даже лучше во viewport (там они от 0 до 1);
2) а дальше уже дело техники пересчитать в координаты на канвасе.
3) делать каждый кадр
4) профит
- Вконтакте



freeExec, почему не работает код из примера?
Выдаёт MissingComponentException: There is no ‘Camera’ attached to the «Canvas» game object, but a script is trying to access it.
You probably need to add a Camera to the game object «Canvas». Or your script needs to check if the component is attached before using it.
Как UI элемент привязать к спрайту
Есть к примеру хелсбар в канвасе, который динамически создается, есть спрайт юнита. Собственно как преобразовать этот хелсбар(scale, position), что бы он отобразился на спрайте(сверху, ну с офсетом я разберусь) c преобразованным скейлом и позицией?
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.