- Home /
Dont Destroy On Load - Exception
what i want to do is a bit hard to explain so i will try to be the maximum comprensible as i can.
i have 2 scenes.
and i have my menu manager that doesnt destroy on load with the command line: DontDestroyOnLoad();
and he pass from the scene 1 to scene 2
but when i pass from the scene 2 to scene 1 it duplicates, i just want to stay with the first menu manager.
there is a way to destroy the default menu manager from scene 1 when i pass from the scene 2 to scene 1 ?
As always comprehension will be helped by proper capitalisation.
Answer by Kiwasi · Aug 12, 2014 at 12:25 AM
What you are after is the singleton pattern. Goes something like this
public class MenuManager : MonoBehaviour {
public static MenuManager instance;
void Awake (){
if(!instance){
instance = this;
} else {
Destroy(gameObject);
}
}
}
Answer by rutter · Aug 12, 2014 at 12:16 AM
You're looking for some variety of singleton pattern:
http://forum.unity3d.com/threads/unity-tips-the-singleton-pattern.144731/
http://answers.unity3d.com/questions/20949/singleton-implementation.html
Process is fairly simple, but important to get right:
You must keep track of a single, static "instance" of the class.
Once loaded, your object must check if there is currently any instance registered.
If there is not an instance, your object should become the new instance.
If there is an instance, you should resolve that; usually, you'll either destroy the new object, or destroy and replace the old one.
Code examples are fairly trivial if you understand enough programming to know what a static variable is. If not, time to look up some tutorials!
The links above should be helpful for additional explanation.
Your answer
![](https://koobas.hobune.stream/wayback/20220613160403im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
DontDestroyOnLoad Slowing Loading Down 0 Answers
GameObject::scene and DontDestroyOnLoad() 0 Answers
Keep gameObjects states between scenes without duplicating 1 Answer
I have an error, script should check for null or not destroy game objects 2 Answers
good resource about conserving memory when multiple levels share resources? 0 Answers