- Home /
String to float conversion decimal problem
I am importing .txt data containing XYZRGB values generated with Matlab into Unity. Even though RGB values seem odd to me, when manually checked, colors are correct. When I run the whole program, float values of colors and positions are not ok. I can change the position so it matches the values in .txt data with some dividing but can't do that for rgb values (see attached picture). Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
public class GenerateBalls : MonoBehaviour
{
private GameObject colormap;
List<xyzdata> xyzdata = new List<xyzdata>();
// Start is called before the first frame update
void Start()
{
TextAsset XYZRGB = Resources.Load<TextAsset>("XYZRGB"); // Load text asset (asset is in string)
string[] data = XYZRGB.text.Split(new char[] { '\n' }); // Split by new lines, create array
Debug.Log(data.Length);
for (int i = 0; i < data.Length; i++) // Read each line
{
string[] row = data[i].Split(new char[] {','}); //Split on commas
xyzdata q = new xyzdata();
float pos_x = float.Parse(row[0]);
float pos_y = float.Parse(row[1]);
float pos_z = float.Parse(row[2]);
float col_r = float.Parse(row[3]);
float col_g = float.Parse(row[4]);
float col_b = float.Parse(row[5]);
// For unity console
q.xdata = row[0];
q.ydata = row[1];
q.zdata = row[2];
q.r = row[3];
q.g = row[4];
q.b = row[5];
xyzdata.Add(q);
colormap = GameObject.CreatePrimitive(PrimitiveType.Sphere);
colormap.transform.position = new Vector3(pos_x, pos_y, pos_z);
colormap.GetComponent<Renderer>().material.color = new Color(col_r, col_g, col_b);
colormap.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
}
foreach (xyzdata q in xyzdata)
{
Debug.Log(q.r);
}
}
}
Here is the link to the picture of the problem and original .txt file: https://we.tl/t-nih1xaZW1N
So the question is, how can I modify my script so that the XYZ and RGB values will be executed according to values in imported text file.
I uploaded the link with the files. But basically when I am changing line 41 and putting in values manually like (0.5, 0, 0) colors are correct, but when I put in variables (col_r, col_g, col_b) then colors do not appear correctly. Same think I noticed in line 40 with positions which are not in -0.35, -0.85, -0.0958 format but -35,-85,-95845. I fixed this with some dividing but can't to that for colors.
Answer by xxmariofer · Feb 28 at 11:22 AM
I have had this issue in the past, in my case was because I am from spain, and in my place floats decimals where with ',' instead of '.' (or vicebersa dont remember) try something like this
float.Parse(row[0], CultureInfo.InvariantCulture);
Your answer
![](https://koobas.hobune.stream/wayback/20220613053450im_/https://answers.unity.com/themes/thub/images/avi.jpg)