- Home /
How to read X and Y component ( of a vector2) from a list
I have a code in C# //public void OpenCityList(string fileName) // { // DataSet cityDS = new DataSet();
// try
//{
// this.Clear();
// cityDS.ReadXml(fileName);
// DataRowCollection cities = cityDS.Tables[0].Rows;
// foreach (DataRow city in cities)
// {
// this.Add(new City(Convert.ToInt32(city["X"], CultureInfo.CurrentCulture), Convert.ToInt32(city["Y"], CultureInfo.CurrentCulture)));
// }
// }
// finally
// {
// cityDS.Dispose();
"City ( int X, int Y) " exists in another class.
I have some points ( vector 2) that I inserted in Inspector, and I want to make a list (listOfCities) from them and then separate X and Y component of each point to insert into "City ( int X, int Y) " later.
public Vector2[] interestPoints;
public List <Vector2> listOfCities;
void Start () {
foreach (Vector2 value in interestPoints) {
listOfCities.Add (value);
this.Add (new City ( Convert.ToInt32( value.X), Convert.ToInt32(value.Y)));}
I started with this. Is it right?
Answer by jeffreyrampineda · Nov 22, 2017 at 09:20 PM
You can add a Vector2 field inside the City class and have the constructor set the received Vector2 value. Then change your listOfCities to a List of City class. If you wanna access the city's Vector2, just access it through listOfCities[0].location.x . Also, I think when accessing Vectors, it's lower case "x" or "y" https://docs.unity3d.com/ScriptReference/Vector2.html :
// City
public class City {
public Vector2 location;
public City(Vector2 loc){
location = loc;
}
}
// in your code
public List <City> listOfCities;
void Start (){
foreach(Vector2 value in interestPoints){
listOfCities.Add(new City(value));
}
}
//Accessing city's Vector2
listOfCities[0].location.x;