- Home /
Nested Lists "Add" method problem
Hello there,
for reasons I need a List of Vector2-Lists:
List<List<Vector2>> occludedObjects;
void someInitFunction(){
occludedObjects = new List<List<Vector2>>();
List<Vector2> occludedPoints = new List<Vector2> ();
occludedObjects.Add (occludedPoints);
}
Now when I add a new Vector2 to a sublist, every sublist will overwrite it's content with this Vector2. Clearing any sublist seems to clear the other sublists, too. Here is how I'm trying to do things:
occludedObjects[0].Clear();
occludedObjects[0].Add (new Vector2(0f, 0f));
occludedObjects[0].Add (new Vector2(0f, 1f));
I guess I am missing some basic nested lists business :( If this is not the source of the problem, i will try and dig deeper into my script.
Help (especially noob friendly) is very, very appreciated!
Answer by Dave-Carlile · Jun 28, 2015 at 07:11 PM
This is adding the exact same list instance each time...
List<Vector2> occludedPoints = new List<Vector2> ();
occludedObjects.Add (occludedPoints);
They all point to the same object, so it doesn't matter which object reference you use, it's going to add to the same list. You need to create a new instance each time, so...
occludedObject.Add(new List<Vector2>());
Now each list entry in occludedObjects
will point to a separate instance.
Wow, thank you so much. It works perfectly. I thought it would add a new copy / instance of the "occludedPoints" List, not reference back to it. But it's totally logical.
Now I feel really stupid :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613201504im_/https://answers.unity.com/themes/thub/images/avi.jpg)