【发布时间】:2014-11-20 19:17:04
【问题描述】:
我正在使用 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;
}
【问题讨论】:
-
您检查过“深度复制或克隆”吗?这是一些例子stackoverflow.com/questions/4054075/…
-
我试过深拷贝。但是,当它要求我将“UnityEngine.Vector2”设置为可序列化时,我放弃了它。