nothing
nothing

Reputation: 151

float.Parse no longer working in Unity (C#)

I had a working project with the following lines of code

 public InputField mass;
 float val = float.Parse(mass.text);

Pretty straighforward, an user puts an ammount of mass and it gets parsed from text to float, this was working perfecitly fine days ago, I was even able to export the project several times, no issues whatsover.

Today I returned to make some changes, before doing so I test it out and get this error.

FormatException: Invalid format. System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Double.cs:209) System.Single.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Single.cs:183) ControlMasa.Update () (at Assets/Scripts/ControlMasa.cs:47)

I have no idea why it suddendly stopped working, not as if I had updated the version of Unity or anything, one day it was working and the next it wasn't.

What's the problem, what can I do?

Upvotes: 0

Views: 5692

Answers (2)

Ginxxx
Ginxxx

Reputation: 1648

Given from your question

InputField mass = null; // assign this first
float mass_ = "0.1f" //sample value
if(float.TryParse(mass.text, out mass_))
{
    /// everything is ok
}
else
{
    /// something wrong. mass.text has incorrect float value
}

Try instead of Parse a TryParse function .

Upvotes: 0

evayly
evayly

Reputation: 850

You are not assigning a FormatProvider, which may cause errors depending on your System. You could try

float var = float.Parse(mass.text, CultureInfo.InvariantCulture);

given that mass.text will always be a valid float number. As you are dealing with Unity you might also want to try

float var = float.Parse(mass.text, new CultureInfo("en-US").NumberFormat);

which will always parse the float in standard US format (with a dot).

However, there might also be other Problems in your code, e.g. maybe the string isnt always a parsable float, you might want to use TryParse instead or make sure it can always be parsed to a float representation.

Upvotes: 4

Related Questions