Hi everyone,
I’ve written a little custom class for some utility regarding numeric settings (e.g. minimum and maximum map size, and alike).
[System.Serializable]
public abstract class ClampedValue<T>
{
[field: UnityEngine.SerializeField] public T Min { get; protected set; }
[field: UnityEngine.SerializeField] public T Max { get; protected set; }
[UnityEngine.SerializeField] protected T val;
public abstract T Value { get; set; }
public ClampedValue(T value, T min, T max)
{
Min = min;
Max = max;
Value = value;
}
}
[System.Serializable]
public class ClampedInt : ClampedValue<int>
{
public override int Value
{
get => val;
set
{
val = Mathf.Clamp(value, Min, Max);
}
}
public ClampedInt() : this(default(int), int.MinValue, int.MaxValue) { }
public ClampedInt(int value, int min, int max) : base(value, min, max) { }
}
I also want to add a custom Property Drawer to that to make displaying them in the Inspector a little less verbose.
[CustomPropertyDrawer(typeof(ClampedInt))]
public class ClampedIntDrawer : PropertyDrawer
{
private static readonly int controlHash = "Foldout".GetHashCode();
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
ClampedInt target = (ClampedInt)property.boxedValue;
label = EditorGUI.BeginProperty(position, label, property);
int indent = EditorGUI.indentLevel;
int id = GUIUtility.GetControlID(controlHash, FocusType.Keyboard, position);
Rect prefix = EditorGUI.PrefixLabel(position, id, label);
Rect sliderPos = prefix;
EditorGUI.indentLevel = 0;
target.Value = EditorGUI.IntSlider(sliderPos, target.Value, target.Min, target.Max);
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
That should give me a slider that is constrained from a ClampedInt’s Min value to its Max value, allowing me to slide up and down to change its current value. And although the slider is displayed correctly (i.e., it is shown, the initial value is correct and the handle is placed correctly in regards to its min and max values), I can’t interact with it.
With Debug.Log() I already checked that the Slider does register the value change but it is instantly reverted. It applies the new value to the ClampedInt field and is then instantly reverted to the original value and I don’t know why. Can anybody help me with that?
Thank you in advance!