Hi! As slider in UIElements is missing value field, I wanted to create my own component with it. After long struggles I made it work. This is how it looks and code is in bottom of the post:
What I did is, that I derived this control from SliderInt class and added IntegerFiled. But I have these questions:
1] to synchronize value between original slider control and integer field, I had to register value changed callback to integer field. When value of field is changed, I call setter of value property (which I overriden). In it I am setting value of slider (which is binded to object I am editing). When value is changed with slider knob, value setter sets also value of integer field.
Is this way of synchronization correct? First I tried to copy bindingPath of slider into bindingPath of integer field in constructor, but it did not work (probably binding is set after construction and it would not also reflect changes in binding later). Is there any way how control can get notified when binding is set or changed?
2] styles. How can I style integer field inside this control from C# code or from UXML (just inline, not USS)? I have access only to slider control, which is container for label, visual input (which conatins slider track and slider knob) and integer field. I found, I can style my integer field from USS if creating style like bellow, but I may want to adjust only one slider directly with style attribute in UXML (like different background color of field, etc.):
SliderWithValue IntegerField {
margin: 0px 5px;
}
Code for Int slider with value:
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace MyElements {
public class SliderWithValue : SliderInt {
public new class UxmlFactory : UxmlFactory<SliderWithValue, UxmlTraits> { }
private readonly IntegerField _integerElement;
public override int value {
set {
base.value = value;
if (_integerElement != null) {
_integerElement.SetValueWithoutNotify(base.value);
}
}
}
// ---------------------------------------------------------
public SliderWithValue() : this(null, 0, 10) {
}
// ---------------------------------------------------------
public SliderWithValue(int start, int end, SliderDirection direction = SliderDirection.Horizontal, float pageSize = 0)
: this(null, start, end, direction, pageSize) {
}
// ---------------------------------------------------------
public SliderWithValue(string label, int start = 0, int end = 10, SliderDirection direction = SliderDirection.Horizontal, float pageSize = 0)
: base(label, start, end, direction, pageSize) {
_integerElement = new IntegerField();
_integerElement.style.width = 30;
_integerElement.style.flexGrow = 0;
_integerElement.RegisterValueChangedCallback(evt => {
value = evt.newValue;
});
Add(_integerElement);
_integerElement.SetValueWithoutNotify(value);
}
}
}