我正在 Unity3D 中开发一个小型应用程序/游戏。
问题是: 我需要克隆一个数组(称为 tempArray)并对其进行一些修改。然后我需要将 MAIN 数组的值更改为修改后的 tempArray。但是,每当我对克隆数组进行更改时,都会对主数组进行相同的更改。
所以我使用了以下代码:
private Cell[,] allCells = new Cell[256, 256];
private Cell[,] cellClone = new Cell[256,256];
//meanwhile initiated to some values//
//Here i clone the array.
cellClone = (Cell[,])allCells.Clone();
//Here i output the values for an element from both arrays.
Debug.Log(cellClone[0, 0].region.name.ToString());
Debug.Log(allCells[0, 0].region.name.ToString());
//Here i want to change "Region" variable of cellClone ONLY.
cellClone[0, 0].setRegion(new Region("testregion123", Color.cyan, false));
//Finally, i output the same values again. Only cellClone should change.
Debug.Log(cellClone[0, 0].region.name.ToString());
Debug.Log(allCells[0, 0].region.name.ToString());
但是,输出显示 allCells[0,0] 元素也已更改。这意味着我对克隆数组所做的任何操作都会在主数组上执行。
编辑:
经过大量尝试后,我将其作为解决方案实现。我发布此内容是为了防止有人遇到类似问题。
但我不确定这是否应该这样做,所以如果有人有任何信息 - 我会检查这篇文章。
for (int i = 0; i < allCells.GetLength(0); i++)
{
for (int j = 0; j < allCells.GetLength(1); j++)
{
//cellClone[i, j] = allCells[i, j].Clone();
//cellClone[i, j] = new Cell((int)allCells[i, j].position.x, (int)allCells[i, j].position.y, allCells[i, j].getRegionName());
cellClone[i, j] = allCells[i, j].clone();
}
}
以及克隆功能:
public Cell clone()
{
Cell n = new Cell((int)position.x, (int)position.y, regionName);
return n;
}
最佳答案
However, the output shows that allCells[0,0] element was also changed. This means that any operation I do to the cloned array, is executed to the main array.
除非 Cell
是一个结构体,否则您的 setRegion
方法(听起来它实际上应该只是一个 Region
属性)不会改变数组的内容。它正在更改存储在两个数组都包含引用的对象中的数据。
您正在执行数组的浅克隆,这意味着正在复制引用 - 但每个 Cell
对象未被复制克隆的。 (我们甚至不知道该操作是否已在 Cell
中实现。)
听起来您想执行深度克隆,例如:
for (int i = 0; i < allCells.GetLength(0); i++)
{
for (int j = 0; j < allCells.GetLength(1); j++)
{
cellClone[i, j] = allCells[i, j].Clone();
}
}
...您需要自己实现 Clone
方法。 (例如,它可能需要依次克隆该区域。)
关于c# - Unity C# 数组 - 如何克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27047697/