Search Unity

InputField float.Parse Problem

Discussion in 'Scripting' started by TheStrongSkye, Oct 1, 2018.

  1. TheStrongSkye

    TheStrongSkye

    Joined:
    Oct 29, 2016
    Posts:
    23
    Hello
    I want to make a mouse sensitivity option like that:

    I want to make InputField and Slider values equal.
    I've tried this:
    Code (CSharp):
    1. mouseSensitivitySlider.value = float.Parse(mouseSensitivityInput.text);
    But it gives that error:
    Code (CSharp):
    1. FormatException: Invalid format.
    2. System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Double.cs:209)
    3. System.Single.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Single.cs:183)
    4. SettingManager.Update () (at Assets/#Only Alone/Skrypty/SettingManager.cs:88)
    5.  
    How can i fix that ?
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi @thestrongskye

    It probably works just fine, until you change the input field to something that is not parseable...
    this is when you get the error, I think.

    You could do something like this instead:

    Code (CSharp):
    1.  
    2. float result;
    3.  
    4. if (float.TryParse(inputField.text, out result))
    5. {
    6.     Debug.Log("Test:" + result);
    7. }
    8.  
    This is just an example.

    Result gets assigned only when string value can be parsed as float. So in this case, the Debug log doesn't print if you write something like "2.3abc" in the input field.
     
  3. TheStrongSkye

    TheStrongSkye

    Joined:
    Oct 29, 2016
    Posts:
    23
    Thank you! It worked:
    Code (CSharp):
    1.         if (float.TryParse(mouseSensitivityInput.text, out parseresult))
    2.         {
    3.             mouseSpeed = (mouseSensitivitySlider.value = parseresult);
    4.         }
    Now i need to do 2 more things:
    -Make a min and max values for input field (range)
    -After typing "2" in input field for example, i want to automatically add ".00" - so it will be "2.00"

    For min and max values i've tried this:
    Code (CSharp):
    1. (mouseSpeed) = (Mathf.Clamp(mouseSpeed, 0.1f, 10));
    but it won't work
    Any suggestions how can i do those things ?
    Thanks for help :)