Hi All,
I’m very inexperienced in coding and unity. I’m trying to move gameobject by reading csv or txt file. Basic circle or rectangle is enough for the beginning. I would be happy if you helped me.
I found this code on the web but it moves on one way forever:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
public class CSVFIleReader : MonoBehaviour
public GameObject Cube;
public TextAsset csvFile;
// Update is called once per frame
void Update()
{
readCSV();
}
void readCSV()
{
string[] records = csvFile.text.Split('
‘);
for (int i = 1; i < records.Length; i++)
{
string array = records*.Split(’,');*
var pos = new Vector3(float.Parse(array[0]), float.Parse(array[1]), float.Parse(array[2]));
}
}
Text file:
speed,x,y,z
1,0,0,1
1,0,2,1
1,0,4,2
Hellium
2
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CSVFIleReader : MonoBehaviour
{
private struct Step
{
public float speed;
public Vector3 destination;
}
public Transform Cube;
public TextAsset CsvFile;
private List<Step> steps;
private int currentStep = 0;
void Start()
{
ReadCSV();
Cube.position = steps[0].destination;
}
void Update()
{
if((Cube.position - steps[currentStep].destination).sqrMagnitude < 0.1f)
currentStep = (currentStep + 1) % steps.Count;
Cube.position = Vector3.MoveTowards(Cube.position, steps[currentStep].destination, steps[currentStep].speed * Time.deltaTime);
}
void ReadCSV()
{
steps = new List<Step>();
string[] records = CsvFile.text.Split('
‘);
for (int i = 1; i < records.Length; i++)
{
string array = records*.Split(’,');*
steps.Add(
new Step()
{
speed = float.Parse(array[0]),
destination = new Vector3(float.Parse(array[1]), float.Parse(array[2]), float.Parse(array[3]))
}
);
}
}
}
Hi @Hellium thanks for the latest answer.
What should be added to code in order to read and take the position of the line:
Children (0):
Static Translation: (15.0503, 34.1802, -118.183)
from the whole text?
another one: what if there is a had or something of the object must look at the side of the movement? can be adjustable?
Hi @Hellium it works super nice. Do you know how to rotate one side of the object into movement side?