我在Unity3D中開發一個小應用/遊戲。Unity C#Array - 如何克隆
問題是: 我需要克隆一個數組(對其調用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;
}
你有簽出'深拷貝或克隆嗎??這裏是一些例子http://stackoverflow.com/questions/4054075/how-to-make-a-deep-copy-of-an-array-in-c – MethodMan 2014-11-20 19:21:11
我試過深層複製。但是,當我要求將「UnityEngine.Vector2」設置爲可序列化時,我放棄了它。 – Szlosestack 2014-11-20 19:53:54