- Home /
Instantiate from persistent GameObject
Hello,
I have recently started working on a script that is supposed to store an array of GameObjects at one scene to be instantiated at another, but the GameObjects don't persist when changing scenes. Are there any tricks available to change that? the script itself is attached to an empty GameObject with DontDestroyOnLoad enabled.
How can the script know what to instantiate if the GameObjects doesn't exist anymore, you have to persist them too.
That's the question :P
Ideally I would have made a prefab out of the GameObject and stored it, but that doesn't seem to be possible. Using DontDestroyOnLoad makes a mess when objects are duplicated so I am not sure how to get around that.
Answer by Brian Stone · Aug 21, 2012 at 08:09 PM
When you load a new scene, the scene list is cleared and all objects in the current scene are destroyed. If you don't want this to happen, then you have to explicitly set the DontDestroyOnLoad property to true for each object that you want to preserve for the next scene.
http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
Edit: I guess I didn't read your question thoroughly enough. Sounds like you're already doing this.
The GameObject the script was attached to was first started in an "initialise" scene that I wouldn't need to go back to, but these objects are in scenes that will frequently be visited by the player, leading to duplication issues that I haven't managed to solve.
If I could solve that, would it be possible to disable the GameObject until the player visits the appropriate scene, removing the need to instantiate it?
Answer by Kergal · Aug 21, 2012 at 08:33 PM
mh, i am still a newbie and i am sure there is a better way, but how about something like giving each entry of the array a key store the key in f.e. the playerprefs then in the new scene if the key exists - recreate the objects (or even the whole array again).
Answer by Kergal · Aug 21, 2012 at 08:33 PM
mh, i am still a newbie and i am sure there is a better way, but how about something like giving each entry of the array a key store the key in f.e. the playerprefs then in the new scene if the key exists - recreate the objects (or even the whole array again).
Answer by MathieuBarbier · Aug 21, 2012 at 08:42 PM
You might put those objects under a parent that has the dontdestroy property.