- Home /
How to spawn objects from CSV file
Hello,
I have been trying to work out a code for awhile now that reads a CSV file, parses the data, and then plots objects based on that data (x,z). Although I am able to parse the CSV file and print the array, I am not understanding how to instantiate objects based on this data.
I have hit a roadblock and really not sure what to do at this point. Does anyone have any suggestions please? Thank you
#pragma strict
//This code is used to parse a CSV file and also to spawn objects based on that CSV fi
// Big thanks to Seth Iacangelo aka Dark Shot of FF XIV
var csvFile : TextAsset;
var prefab : GameObject;
var x = new Array();
var y = new Array();
var z = new Array();
var count = new Array();
var id = new Array();
var j = 0;
function Start(){
Longitude();
print();
}
function Longitude () {
var stringArray = csvFile.text.Replace("\n"[0],","[0]).Split(","[0]);
for(var i = 3; i < stringArray.length; i+=1){
switch (i%3)
{
case 0:
x[j] = stringArray[i];
break;
case 1:
y[j] = stringArray[i];
break;
case 2:
z[j] = stringArray[i];
j = j + 1;
break;
}
}
}
// Test to see if the array in longitude can be accessed from without. Eventually this code needs to spawn the prefabs
function print(){
for(var t = 0; t < x.length; t+=1)
{
var block = Instantiate(prefab);
block.transform.position = new Vector3(0+t, 0, 0+t);
print("The coordinates for line " + x[t] + " are " + z[t] + "." + " Height = " + y[t]);
}
}
Please edit your question and share the code that is not working otherwise we can't help.
Answer by Tomer-Barkan · Dec 01, 2013 at 05:51 AM
Your problem is in setting the position (assuming your CSV file is in the right format for this script). t
is the iterator that you use to iterate over the array. So x[y] are the x coordinated, y[t] are the y coordinates, and z[t] are the the coordinates.
Now, when you print, you print correctly (you print x[t], z[t] and y[t]), but when setting the position, you use the iterator itself as the value (you use 0+t).
So change the position setting line to:
block.transform.position = new Vector3(x[y], y[t], z[t]);