- Home /
The question is answered, right answer was accepted
DontDestroyOnLoad problem
Hi!
I have a problem in using of DontDestroyOnLoad method. I have empty gameObject (SciptObject) with SomeScript in it. Script has public variable "Button", this variable is filled in Unity editor (dragged button to an empty field in script properties in Inspector window). For this script I`m using DontDestroyOnLoad:
DontDestroyOnLoad(this.gameObject);
After some actions I`m loading another scene and the loading the first scene and one more ScriptObject is created with empty variable Button.
Is it posible to destroy new ScriptObject and use the first one?
Thanks!
I can't give you a script right now, but the word you're looking for is a "singleton" object.
Answer by rockyourteeth · Oct 13, 2015 at 02:18 PM
What is the public variable "Button"? Is it another GameObject? If so, then that object is probably getting destroyed, and therefore, the original instance of your singleton object, which had a reference to the Button in the old level, now doesn't have a reference to this new Button in this new version of the level.
If this is the case, you'll need to find the object through script on Level Load, using Find, or Find by Tag, or something like that.
variable:
public Button OpenButton
What about using a prefab of the gameObject which has this variable Button filled with my content from the scene?
Prefabs can't reference objects in the scene. Think about it, a prefab exists outside of your scene (until you instantiate it), so it can't reference something inside the scene, because you could instantiate that prefab in another scene, and then you'd end up with a bad reference because that object isn't there.
So, no, sorry, that won't work.