Hello everyone, I'm enjoying Unity but Im having trouble with Lists in C#, and from googling, I think my approach is all wrong.
In my game, when the player dies they leave behind a trail of waypoints. When they respawn, a new AI character also spawns and follows the waypoints. I've got this working fine by storing the waypoints in a List and using a Navmesh agent.
I'm having problems when the player dies more than once and having different AI's follow different sets of waypoints. To create a new set of waypoints, I tried clearing the List just after I've instantiated the character and sent it the waypoints its should follow. The problem with this I believe is that because Lists are a reference type, the AI's List to follow also gets cleared.
How can I make a copy of this List which won't also get cleared?
The only other way I could think of was to make a List of Lists that don't get cleared, but I can't seem to find much about this which suggests there's a better way.
Any help at all would be awesome. - Thanks
When you do this
you're indeed simply creating another reference to the list that waysIn already points to. Since both references refer to the same internal datastructure, clearing out that list will result in two references that both point to the cleared list. You need to do a shallow copy of the list instead (one that copies all the references - as opposed to a deep copy, which would create actual value copies of each element).
The easiest way to do a shallow copy is to iterate over the old list and add its references to the new list:
There's a lot of ways to skin this cat, as you can see if you google "c# list shallow copy". But this might be enough for your purposes.