Olivier Giniaux
Olivier Giniaux

Reputation: 950

Assign static List to a non-static List

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 :

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

Answers (1)

Ant P
Ant P

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

Related Questions