I’m new to the UI Toolkit so a bit of a 2 part question here.
Firstly, if i’ve got a script with a simple List players and Player has string Name and int Health, i want to display this in a custom UI element. I can Create a custom UI element with a couple of labels & a button, how do i bind the properties of these labels to Name and Health?
Secondly, how do i add a collection of those custom UI elements to something like a ScrollView control?
This is all simple enough to do in the old GUI using prefabs etc but thought i’d have a go with the new one. I’m liking the style sheets and the designer, i’ve been able to achieve most of what i wanted to do so far but kind of came unstuck at this point.
If I understood correctly, you need to create SerializedObject of your class Player. After you should use binding to your fields. You can binding in C# or use BuilderUI or uxml file.
This is your class Player.
public class Player : MonoBehaviour
{
public string Name = "Geralt";
public float Health = 100f;
}
This is your class for UI.
public class PlayerUI : MonoBehaviour
{
private Label healthLabel;
private Label nameLabel;
private void OnEnable()
{
var rootVisualElement = GetComponent<UIDocument>().rootVisualElement; // Get UIDocument component.
nameLabel = rootVisualElement.Q<Label>("name-label"); // Get control of UIDocument. name-label is name of Label.
healthLabel = rootVisualElement.Q<Label>("health-label"); // Get control of UIDocument. health-label is name of Label.
SerializedObject so = new SerializedObject(Camera.main.GetComponent<Player>()); // Create serialization object
rootVisualElement.Bind(so); // Binding to Player class
nameLabel.bindingPath = "Name"; // Binding to Name field.
healthLabel.bindingPath = "Health"; // Binding to Health field.
}
}
Hello! Binding is only available in the Editor right now and it sounds like you’re doing Runtime UI so you’ll have to manually set values in the mean time. We have Runtime bindings on our roadmap but it’s not in the making right now.