[英]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. 我之所以来到这里,是因为我在Unity和C#中遇到了一个奇怪的问题,无法解决该问题。
I have two C# scripts : 我有两个C#脚本:
ScriptA is instantiated one time and has static variables. ScriptA被实例化一次并且具有静态变量。 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). ScriptB被实例化多次(它附加到敌人身上)。 On Start(), it sets a non-static list equal to the current ScriptA.listOfPoint
在Start()上, 它设置一个等于当前ScriptA.listOfPoint的非静态列表。
The issue is that it seems that this non-static list is updated with the ScriptA.listOfPoints
. 问题在于,似乎此非静态列表已使用
ScriptA.listOfPoints
更新。 I just want to have a list equal to ScriptA.listOfPoints
state when this ScriptB was instantiated. 我只想在实例化此ScriptB时有一个等于
ScriptA.listOfPoints
状态的列表。
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;
}
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
. 这将创建一个新列表,并复制传递到构造函数的列表中的元素,因此现在可以独立于
listOfPoints
来操纵nonStaticListOfPoints
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.