Instantiate - Getting specific data from another script
For my final in class I am being asked to visualize data. I've taken earthquake data from an Excel file an converted it to a TXT. In that data set there are multiple columns including Latitude and Longitude.
I am trying to call those specific variables from that data and to create a sphere for each piece. In other words, for every line of data a sphere is going to be created with that specific latitude and longitude. But right now I'm getting an error that reads:
NullReferenceException: Object reference not set to an instance of an object LevelScript.Start () (at Assets/Classes/LevelScript.cs:24)
Here is the data so it matches:
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO;
public class LevelScript : MonoBehaviour {
public TextAsset earthquakeDataFile;
EarthquakeStruct[] earthquakeStructs; // penguins
// Use this for initialization
void Start ()
{
earthquakeStructs = ParseEarthquakeFile();
for (int i = 0; i < 1; i++)
{
// instantiate that sphere
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.AddComponent<EarthquakeStruct>();
sphere.transform.position = new Vector3(0, 0, 0);
// set the variables in that sphere to the same as the ones in our struct
float tempLat = earthquakeStructs[i].GetLatitude();
float tempLong = earthquakeStructs[i].GetLongitude();
**sphere.GetComponent<EarthquakeStruct>().SetLatitude(tempLat);
sphere.GetComponent<EarthquakeStruct>().SetLongitude(tempLong);**
// call function to move gameobject to latitude / longitude location
sphere.GetComponent<EarthquakeStruct>().MoveToLocation();
}
}
// Update is called once per frame
void Update ()
{
}
private EarthquakeStruct[] ParseEarthquakeFile()
{
EarthquakeStruct[] temp = new EarthquakeStruct[0]; // make empty array
//read text file
string earthquakeFile;
earthquakeFile = earthquakeDataFile.text; // entire file
if (earthquakeFile != null)
{
string[] lines = earthquakeFile.Split('#'); //each line
// initialize array
temp = new EarthquakeStruct[lines.Length]; // set length of struct array
for (int i = 1; i < lines.Length; i++)
{
string[] columns = lines[i].Split(','); // each column
// convert into float
float latitude = 0;
float longitude = 0;
if (columns.Length > 15) // has reasonable number of columns for our data set
{
if (columns[1] != null) // isn't a null variable
{
if (columns[1].Length > 0) // not empty
{
latitude = float.Parse(columns[1]); // parse data into float
}
}
if (columns[2] != null)
{
if (columns[2].Length > 0)
{
longitude = float.Parse(columns[2]);
}
}
}
temp[i] = new EarthquakeStruct(latitude, longitude); // set struct info
}
}
return temp;
}
}