- Home /
Deep Cloning using instantiate
I currently have a GameManager that holds a List of levels. I have a LevelManager that when it starts will get the currentLevel from the GameManager which is an instantiated clone of the level that is selected. I have an array of WordLengthRequirements(scriptable object) that gets changed when an objective is completed. For some reason when I modify the array objects is changes the List of levels object that was originally cloned. but only the array of WordLengthRequirements. All other variables are seperate and are always seperate.
When I modify currentLevel(Level).wordLengthRequirement it changes the original levels array object. but not when I change something like the name of the currentLevel. I hope this makes sense to you guys and I appreciate your help.
public class WordLengthRequirement : ScriptableObject {
public int length = 0;
public int count;
}
public class Level : ScriptableObject
{
public WordLengthRequirement[] wordLengthRequirement;
}
//from gameManager Script
currentLevel = Instantiate(levels[i]) as Level;
Answer by whydoidoit · Jun 15, 2013 at 07:50 AM
Welcome to Hell :S
Yep you need to clone all of the objects which are scriptable objects within the outer shell, otherwise just a reference is made. I write "Copy" methods that ensure that this happens, but depending on how complicated those scriptable objects are, and if they refer to other things, this can be a really onerous process that has the chance of hard to find bugs. Hopefully yours are just lists etc, in which case just Instantiate the ScriptableObject derivative in your copy function and you're golden.
You could perhaps just call this after instantiating the base object.
currentLevel.InstantiateLevel();
...
public void InstantiateLevel()
{
for(var i = 0; i < wordLengthRequirement.Length; i++)
{
wordLengthRequirement[i] = Instantiate(wordLengthRequirement[i]) as WordLengthRequirement;
}
}