Search Unity

Textbox only allow ints, but also negative ints as well as positive

Discussion in 'Scripting' started by TheRaider, Jan 11, 2014.

  1. TheRaider

    TheRaider

    Joined:
    Dec 5, 2010
    Posts:
    2,250
    How would one do this easily?

    I figured positive only can be done by

    Code (csharp):
    1.  
    2. tempText = GUI.TextField(Rect(0,0,100,100), amt.ToString());
    3.     temp = 0;
    4.     if (int.TryParse(tempText,temp))
    5.     {
    6.         amt = Mathf.Clamp(temp, -90, 90);
    7.         Debug.Log("Vaild");
    8.     }
    9.  
    but it doesn't allow for negative numbers to be entered
     
  2. TheRaider

    TheRaider

    Joined:
    Dec 5, 2010
    Posts:
    2,250
    Well actually this works but if the number if negative but not if you start by typing -
     
  3. Sildaekar

    Sildaekar

    Joined:
    Jul 8, 2013
    Posts:
    95
  4. TheRaider

    TheRaider

    Joined:
    Dec 5, 2010
    Posts:
    2,250
  5. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Love this kind of challenge;

    Code (csharp):
    1.  
    2. public class NumberTextField
    3. {
    4.     private string temp = "";
    5.     private float value = 0;
    6.     private string format = "";
    7.  
    8.     public NumberTextField() { }
    9.  
    10.     public NumberTextField(string format)
    11.     {
    12.         this.format = format;
    13.     }
    14.  
    15.     public float Draw(string label, float value)
    16.     {
    17.         if (this.value != value)
    18.         {
    19.             this.value = value;
    20.             temp = value.ToString();
    21.         }
    22.  
    23.         GUILayout.Label(label);
    24.         string input = GUILayout.TextField(temp);
    25.  
    26.         float result;
    27.         if (float.TryParse(input, out result)  !float.IsInfinity(result))
    28.         {
    29.             temp = result.ToString(format);
    30.             return result;
    31.         }
    32.  
    33.         if (input.Length == 0 || (input.Length == 1  input.StartsWith("-")))
    34.         {
    35.             temp = input;
    36.             return 0;
    37.         }
    38.  
    39.         return value;
    40.     }
    41. }
    42.  
    Right now it's in float, but should be simple enough to turn into integer.
    This class is reusable wherever you want it.