Created
April 27, 2015 15:28
-
-
Save BrianOstrander/a7908b979f12631d86c5 to your computer and use it in GitHub Desktop.
Shallow vs. Deep cloning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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