简体   繁体   中英

How to fix unity FormatException when parse from string to float?

I have text file (presented as timeFile TextAsset). In this file i have string array, with float elements, one per row. Example:

7.9483900
8.392342
1.034224
0.032424323
23.563646346

So i'm split(\\n), and every lines element have one float element. And i have float array, with parsed lines.

But then i'm trying instantiate my prefab with y-position of this float array, I have:

FormatException: Input string was not in a correct format. System.Number.ParseSingle (System.String value, System.Globalization.NumberStyles options, System.Globalization.NumberFormatInfo numfmt) (at :0)

How to fix it?

void Start()
{
    var lines = timeFile.text.Split("\n"[0]);
    var linesFloat = new float[lines.Length];

    for (int i=0; i<lines.Length; i++)
    {
        linesFloat[i] = float.Parse(lines[i], CultureInfo.InvariantCulture);
    }

    for (int i = 0; i<lines.Length; i++)
    {
        var position = new Vector3(0, linesFloat[i], -0.5f);
        Instantiate(projectilePrefab, position, Quaternion.Euler(0,0,0));
    }
}

I tryed CultureInfo.InvarianCulture in float Parse, but that didn't helped me.

re-check your input strings!

it is possible/likely that they still contain a \\r character because windows (clrf) linebreaks are \\r\\n or maybe also a space character.

You could use Trim() to make sure they are left out like eg

for (int i=0; i<lines.Length; i++)
{
    linesFloat[i] = float.Parse(lines[i].Trim('\r', ' '), CultureInfo.InvariantCulture);
}

If you you only want to get rid of the exception you could use TryParse instead.

for (int i=0; i<lines.Length; i++)
{
    if(float.TryParse(lines[i], out var floatValue))
    {
        linesFloat[i] = floatValue;
    }
    else
    {
        Debug.LogFormat(this, "Oops value {0} could not be parsed!", lines[i]);
    }
}

Also note that you can simply use

var lines = timeFile.text.Split('\n');

if there is only one char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM