Skip to content

Instantly share code, notes, and snippets.

@BrianOstrander
Created April 27, 2015 15:28
Show Gist options
  • Save BrianOstrander/a7908b979f12631d86c5 to your computer and use it in GitHub Desktop.
Save BrianOstrander/a7908b979f12631d86c5 to your computer and use it in GitHub Desktop.
Shallow vs. Deep cloning
// The GameObject prefab assigned in the editor before playing the game.
GameObject somePrefab;
void Start() {
// --- Deep Clone ---
// Instantiate a new instance of somePrefab, and asign the reference of it to the instantiatedPrefab variable.
// The Instantiate() method returns an Object, instead of a GameObject, so we have to convert it to a GameObject by putting (GameObject) before it.
GameObject instantiatedPrefab = (GameObject)Instantiate(somePrefab);
// --- Shallow Clone ---
// Here we make another variable called instantiatedPrefabReference that points to the same instance defined by instantiatedPrefab.
GameObject instantiatedPrefabReference = instantiatedPrefab;
// So doing this:
instantiatedPrefab.tag = "exampleTag";
// Is the same as doing this:
instantiatedPrefabReference.tag = "exampleTag";
// But doing this:
somePrefab.tag = "originalTag";
// will NOT change instantiatedPrefab's tag or instantiatedPrefabReference's tag.
// To prove it, let's print them in the console after changing them:
Debug.Log("instantiatedPrefab's tag is "+instantiatedPrefab.tag);
Debug.Log("instantiatedPrefabReference's tag is "+instantiatedPrefabReference.tag);
Debug.Log("somePrefab's tag is "+somePrefab.tag);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment