Search Unity

Clamp FloatField

Discussion in 'UIElements' started by Devi-User, Nov 7, 2018.

  1. Devi-User

    Devi-User

    Joined:
    Apr 30, 2016
    Posts:
    61
    A simple task - I want to limit the value in FloatField to a specific range. I see that FloatField has the ability to subscribe to OnChangedValue, which I probably use to assign a value again if I don’t like it. Suppose I want to limit the value to between 0.5 and 1.

    Code (CSharp):
    1.  
    2. var zoomField = new FloatField();
    3. zoomField.OnValueChanged(s =>
    4. {
    5.     serializedZoomValue = zoomField.value = Mathf.Clamp(s.newValue, .5f, 1f);
    6.     UpdateZoom();
    7. });
    8. zoomField.value = serializedZoomValue;
    9.  
    However, this changes the editable input field if I start typing something outside of the range. So for example, if I want to enter 0.6 instead of 1, then after I write 0, 0.5 will appear in the field and the cursor will remain in the old position. That is, I can not enter 0.6 just like that - I will have to enter 0.65 or 0.56 and subsequently erase the number 5.
    As you know, this is pretty wild.
    Maybe I'm doing something wrong and someone can give me advice on how to do it in such a way that limiting the values does not visually affect the value that is still being entered.

    I am familiar with the isDelayed field, but this is not exactly what I need, because it applies the result after we finish the input. I'm also interested in the case between these two, when the result is applied immediately, but the displayed value does not change while we are in the input field.
     
    Last edited: Nov 7, 2018
  2. Devi-User

    Devi-User

    Joined:
    Apr 30, 2016
    Posts:
    61
    Looks like I found a solution: I save the actual value in OnValueChanged, but I replace textbox value in BlurEvent
    Code (CSharp):
    1. zoomField.RegisterCallback<BlurEvent>(evt => { zoomField.value = realZoom; });
    Looks like it is enough
     
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    221
    We are working on clamping support but yes, right now, you have to work around it a bit. Your Blur-based work around is not bad at all. :)