Search code examples
c#unity-game-engineunity3d-editor

Move an object with csv/txt data - Unity3d


I am trying to move a 3d object using a C# script in Unity3d. The script takes XYZ coordinates from a csv file and then it parses these values to object's position. You can see the script down below:

using System.Collections;
using UnityEngine;
using System.IO;
using UnityEngine.UI;


public class lastPSP1 : MonoBehaviour
{   
    
    public TextAsset csvFile;
    
    void update()
    {
        readtxt();
    }
    
    void readtxt()
    {
        string [] records = csvFile.text.Split('\n');
        for (int i=1; i<records.Length; i++)
        {
            string [] fields = records[i].Split(',');
            
            transform.position = new Vector3(float.Parse(fields[1]),float.Parse(fields[2]),float.Parse(fields[3]));
        }
    }
}

My csv looks like that:

X,Y,Z
3918625.868,18949220.68,-1281153.635
3912210.028,18950540.5,-1281236.88
3905793.931,18951859.08,-1281320.041

I assigned my script to the object,but after I hit play nothing happens. The object remains still. Can you help me please?


Solution

  • C# is case-sensitive; Unity will search for an Update method while you defined an update method (notice the different capitalization). Additionally, you will encounter a System.IndexOutOfRangeException on this line:

    transform.position = new Vector3(float.Parse(fields[1]),float.Parse(fields[2]),float.Parse(fields[3]));
    

    You have three fields, but you're ignoring the first field and trying to use the 2nd, 3rd, and 4th (non-existent) field. Remember; array indexing starts from 0.

    Also, as you're executing the whole for-loop without any waits in the Update() method, you will only see the last position being used. In order to fix this, you'd need to either distribute the call over several update calls (this would mean a delay of a single game frame between setting each position), or by using a coroutine (most probably what you want).

    public class lastPSP1 : MonoBehaviour
    {   
        public TextAsset csvFile;
        
        void Start()
        {
            StartCoroutine(ReadTxt());
        }
        
        IEnumerator ReadTxt()
        {
            string[] records = csvFile.text.Split('\n');
            for (int i = 1; i < records.Length; i++)
            {
                string[] fields = records[i].Split(',');
                
                transform.position = new Vector3(float.Parse(fields[0]), float.Parse(fields[1]), float.Parse(fields[2]));
    
                yield return new WaitForSeconds(1); // this is the delay between each position change
            }
        }
    }