将静态列表分配给非静态列表

Odg*_*Gsf 1 c# static list instance unity-game-engine

我来到这里是因为我对Unity和C#有一个奇怪的问题,我无法弄清楚如何解决这个问题.

我有两个C#脚本:

  • ScriptA实例化一次并具有静态变量.它有一个静态列表,其中包含路径的点.此列表随时间而变化.

  • ScriptB被多次实例化(它附加到敌人身上).在Start()上,它设置一个等于当前ScriptA.listOfPoint的非静态列表

问题是,这个非静态列表似乎更新了 ScriptA.listOfPoints.我只想ScriptA.listOfPoints在实例化ScriptB时有一个等于state 的列表.

我在这做错了什么?

提前致谢 :)

静态的 :

//ScriptA    
public static List<int> listOfPoints = new List<int>();
public static void pathUpdate() //get called every 2secs
{
    //listOfPoints is modified
}
Run Code Online (Sandbox Code Playgroud)

敌人:

//ScriptB
private List<int> nonStaticListOfPoints = new List<int>();
void Start ()
{
    nonStaticListOfPoints = ScriptA.listOfPoints;
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*t P 6

当您进行该分配时,您不会创建两个列表,而是两个包含对同一列表的引用的变量.

如果您想列表的元素的副本,你可以做这个:

nonStaticListOfPoints = new List<int>(ScriptA.listOfPoints);
Run Code Online (Sandbox Code Playgroud)

这将创建一个列表并复制传递给构造函数的列表中的元素,因此nonStaticListOfPoints现在可以独立操作listOfPoints.