Unity C# Array how to clone

Im developing a small app/game in Unity3D.

The problem is: I need to clone an array (call it tempArray) and make some modifications to it. Then i need to change values of the MAIN array to modified tempArray. However, whenever i make changes to cloned array, the same changes are made to the main one.

So i used the following code:

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());

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.


EDIT:

After alot of playing around I implemented this as a solution. Im posting this in case anybody has a similar problem.

But Im not sure if this is how its supposed to be done so if anybody has any information - Ill be checking this post.

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();
    }
}

And the clone function:

public Cell clone()
{
        Cell n = new Cell((int)position.x, (int)position.y, regionName);
        return n;
}
Jon Skeet
people
quotationmark

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.

Unless Cell is a struct, your setRegion method (which sounds like it should really just be a Region property) isn't changing the contents of the array at all. It's changing the data stored in the object that both arrays contain a reference to.

You're performing a shallow clone of the array, which means the references are being copied - but each Cell object is not being cloned. (We don't even know whether that operation has been implemented within Cell.)

It sounds like you want to perform a deep clone, something like:

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();
    }
}

... where you'd need to implement the Clone method yourself. (It may need to clone the region in turn, for example.)

people

See more on this question at Stackoverflow