number = float.parse( GUILayout.Textfield( number.ToString() );
when i start the game i see “0.88” but if i try to edit it i cant put dots, so i cant delete 0.88 and write “0.1” for example, beacouse if i press the dot, nothing happend! why?
It’s probably because of the way you’re assigning and reading it with regard to the textfield. When you type “0” it parses it to the float 0.0, but once you hit “0.” it tries to parse that and fails, so it doesn’t update the textfield to what you put in. That would be my guess anyway.
A method that will work is to only parse the number when you need it. For example, have your text field, but also have a button that, when pressed, sets number to float.parse(myTextfield.text).
Another option is just to try to parse the textfield during OnGUI() but outside your textfield creation statement. This way it will try to parse the number, and if it’s not yet in a readable form (like “0.”) it will just fail and not try again until you type a new character. You can do this with the float.TryParse() method.
if (System.Float.TryParse(GUILayout.Textfield(number.ToString()), out number))
{
//user inputted valid number, do something
}
else
{
//invalid number currently in text field, do nothing
}
Remove the “out” keyword, then it’s Javascript. However, it’s usually better to prevent unwanted characters in the first place instead of using Parse. See my answer here.
In this case Eric, the decimal character is wanted, but the issue comes when he’s typing in the number “92.5” it keeps getting hung up on the “.” when he’s written “92.” and about to press the “5”.
In that sense, my solution still won’t work. I think you need to separate the “number” from the text.
var CurrentInput : string = String.Empty;
function OnGUI()
{
CurrentInput = GUILayout.Textfield(CurrentInput);
var number : float;
if (System.Float.TryParse(CurrentInput, number))
{
//user inputted valid number
}
else
{
//user inputted bad number (or is currently inputting the decimal) so do nothing
//or use regular expressions to see if the user has inputted letters instead of numbers/decimals
}
}
I know the decimal character is wanted, but letters and other characters are not. Just 0-9 plus the decimal. It’s a better user experience to not allow unwanted characters.
For future reference, it looks like with the new JavaScript compiler in Unity3.4 you need to use System.Single.TryParse instead of System.Float.TryParse. Single is a Float.