"Derived" binding in Unity (and UI Toolkit)

Viewed 163

Unity UI Toolkit has a nifty data binding feature, but I'm a bit unclear how to use it in this particular scenario.

I have a GameObject in my game representing a character with a health field, which is a float in the range [0, 1], representing a percentage range from 0% to 100%. I want to display this in the UI as a percentage.

If I just use binding-path naively, it binds it as an unformatted float, which isn't what I want. Instead, whenever the float value changes, conceptually I want a new "derived" binding with my custom formatting logic, and then bind that to the UI. I'm looking for the best option for this in Unity.

JavaFX has something similar in Bindings where you can generate bindings by performing calculations on other bindings.


What I have so far is this:

var label = row.Q<Label>(className: "pawn-health");
label.RegisterCallback<SerializedPropertyChangeEvent>(evt => {
    label.text = evt.changedProperty.floatValue.ToString("0.0%");
});
label.TrackPropertyValue(obj.FindProperty(nameof(Pawn.health)));

This actually does work, but it seems a bit heavy. I don't like that I have to use TrackPropertyValue instead of setting a binding-path.

Looking for suggestions for ways this can be improved or written in a more idiomatic way, or is the expectation that I have to write out code any time I want to format the bound value?

0 Answers
Related