Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

parsing a String

Discussion in 'Scripting' started by wbl1, May 19, 2009.

  1. wbl1

    wbl1

    Joined:
    Apr 22, 2009
    Posts:
    159
    I am reading in a file with point data. Coordinates are delimited by commas. This is all working file ...

    Trouble is the coordinates need to be converted to floats for Vector3.

    The following code yields this error at runtime:

    FormatException: Invalid format.
    System.Double.Parse (System.String s, NumberStyles style, IFormatProvider provider)
    System.Single.Parse (System.String s)
    UnityScript.Lang.UnityBuiltins.parseFloat (System.String value)
    loadCurve.Start () (at Assets\loadCurve.js:46)

    What am I doing wrong ?? Thanks!


    Code (csharp):
    1.  
    2. var pointFile : TextAsset;
    3.  
    4. function Start()
    5. {
    6.     var txt = pointFile.text;
    7.     var points = txt.Split(","[0]);
    8.     Debug.Log("points in file: " + points.length);
    9.    
    10.     var numPoints = points.length;
    11.    
    12.     var line: LineRenderer = GetComponent(LineRenderer);
    13.     line.SetVertexCount(numPoints);
    14.    
    15.     for (var i=0; i<numPoints; i++)
    16.     {
    17.         var coord = points[i].Split(" "[0]);
    18.         var x : float = parseFloat(coord[0]);
    19.         var y : float = parseFloat(coord[1]);
    20.         var z : float = parseFloat(coord[2]);
    21.         line.SetPosition(i, Vector3(x,y,z));
    22.     }  
    23. }
    24.  
     
  2. wbl1

    wbl1

    Joined:
    Apr 22, 2009
    Posts:
    159
    I figured it out. Moral of this story is to be careful with spaces in your input text files.

    This is a problem (note the space after the commas)

    21.0 23.2 1.0, 22.0 34.2 67.0, ...

    This works fine:

    21.0 23.2 1.0,22.0 34.2 67.0,...

    :oops: :D
     
  3. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661