Reputation: 950
I came here because I have a strange issue with Unity and C# and I can't figure how to solve this.
I have two C# scripts :
ScriptA is instantiated one time and has static variables. It has a static list which contains points for a path. This list changes over the time.
ScriptB is instantiated several times (it is attached to enemies). On Start(), it sets a non-static list equal to the current ScriptA.listOfPoint
The issue is that it seems that this non-static list is updated with the ScriptA.listOfPoints
. I just want to have a list equal to ScriptA.listOfPoints
state when this ScriptB was instantiated.
What am I doing wrong here ?
Thanks in advance :)
Static :
//ScriptA
public static List<int> listOfPoints = new List<int>();
public static void pathUpdate() //get called every 2secs
{
//listOfPoints is modified
}
Enemy :
//ScriptB
private List<int> nonStaticListOfPoints = new List<int>();
void Start ()
{
nonStaticListOfPoints = ScriptA.listOfPoints;
}
Upvotes: 1
Views: 1864
Reputation: 25221
When you make that assignment you are not creating two lists but two variables holding references to the same list.
If you want a copy of list's elements, you can do this:
nonStaticListOfPoints = new List<int>(ScriptA.listOfPoints);
This creates a new list and copies the elements from the list passed into the constructor, so nonStaticListOfPoints
can now be manipulated independently of listOfPoints
.
Upvotes: 6