- Home /
Weird issue with List and for loop.
I have a list which contains Vector[]3 values of some GameObjects saved in a database in the form of string. I am trying to assign these values to an array of GameObjects. I am able to retrieve the values correctly which is confirmed by the Debug.Log in the console, however, a weird thing is happening. When I check in the Inspector, all of the gameObjects have the last value from the loop assigned to them. I am posting screenshots and code to explain the issue.
Code:
DataService ds; public GameObject[] Points;
void Start () {
ds = new DataService (Constants.DB_NAME);
List<SceneMain> sceneMains = ds.GetAllSavedScene ();
//Debug.Log (sceneMains.Count + "--------------");
foreach (SceneMain sceneMain in sceneMains) {
//Debug.Log (sceneMain.scene.ToString ());
foreach (ScenePoint point in sceneMain.points) {
Debug.Log ("Saved Points : "+ point.ToString ());
for (int i = 0; i <sceneMain.points.Count; i++) {
string[] temp = point.point_position.Substring(1,point.point_position.Length-2).Split(',');
float x = float.Parse(temp[0]);
float y = float.Parse(temp[1]);
float z = float.Parse(temp[2]);
Vector3 rValue = new Vector3(x,y,z);
Points [i].transform.position = new Vector3 (rValue .x,rValue .y,rValue .z);
Debug.Log ("Restored Points ; " + Points [i].transform.position);
}
}
}
@corpsinheretoo Please help.
Answer by corpsinheretoo · Apr 02, 2017 at 11:30 PM
I think the trouble comes from the fact that you have in indexed loop
for (int i = 0; i <sceneMain.points.Count; i++)
inside a foreach loop
foreach (ScenePoint point in sceneMain.points)
Your indexed loop keeps counting up but is reusing the same point from the foreach loop (which is independent from your index). I suggest removing the foreach loop and set
point = sceneMain.points[i]
at the beginning of the indexed loop.
Your answer
Follow this Question
Related Questions
Outputting data to CSV file from multiple lists at specific Headers in the CSV? 0 Answers
Check if specific object exist in list or array, Best Practices? 2 Answers
Copy values between two classes in two lists. 1 Answer
my wave spawner not working properly 1 Answer
How do I make a list of lists? 2 Answers