Unity C# Deep Copy

In my latest placement at a games company (more on that in a later post when I can talk about things I did in more detail) I often came across the need to write helper functions for things I was doing often. These actually ended up being quite fun to write and I may continue writing more as I search for a new job. Bare in mind I’m still fairly new to Unity with less than a years experience so the following may be common knowledge to most but it was new for me.

A particular issue I ran into was when trying to trying to copy an Array of GameObjects to another and later editing the initial array.  The options I saw in the on-line C# documentation were both for shallow copying, both Array.Copy and Array.Clone just copy over references to the elements in the starting array rather than doing a deep copy which is what I wanted.

The way I got around this was by taking advantage of the Instantiate function in Unity which also refers to “cloning” but in this case it’s doing it on an individual element within a for loop effectively severing the tie with its cousin so to speak. Finally you have to make sure to cast back to a GameObject as Instantiate just returns a generic Object.

void DeepCopyArray(GameObject[] arrayToCopy, GameObject[] arrayToPaste)
{
	int length = arrayToPaste.Length;
	for (int i = 0; i < length; i++)
	{
		arrayToPaste[i] = (GameObject)Instantiate(arrayToCopy[i]);
	}
}

Again this is fairly basic stuff and there may be a C# or Unity function hidden somewhere for deep copying (though I couldn’t find one at the time) but I felt happy with my mini victory. This could be extended to make sure that both arrays are the same size before doing the copy and also potentially to make sure that you haven’t put the same array in twice.