I use singletons regularly and they work just fine, but I was thinking about exactly how they work and some things don’t make sense to me. For the sake of argument, I’m using this basic structure of a singleton:
public static SingletonExample Instance {get; private set;}
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
Destroy(gameObject);
}
Okay, so based on this I have some questions:
- Does DontDestroyOnLoad() actually makes a duplicate copy of the object into the next scene? It seems to me that it does, considering that if I return to the original scene again I end up with 2 copies of the object, hence the main reason for using a singleton (to destroy the duplicate).
- When I return to the original scene I temporarily have 2 copies of my object until my duplicate singleton destroys itself. During that time before the duplicate gets destroyed, what is my static Instance referencing if I have 2 of them in the scene and it can only reference one thing?
- When I return to my original scene, which copy of my singleton runs its Awake() method first? This is actually the original reason for me trying to understand this, because the singleton specifically destroys THIS gameObject, not the OTHER gameObject, which worried me that it would not maintain any non-static changes that have occurred in the class since it was duplicated into another scene. But of course this does actually work… If I bring my singleton into scene 2, update a value in it, then bring it back to scene 1 the values remain updated in scene 1. How is that possible if I’m destroying the copy of the singleton that I brought with me from scene 2 back to scene 1, and keeping the version of the singleton from scene 1 which did not get updated? The only possible reason I can think of is that actually the original singleton that was left in scene 1 runs its Awake() method first and destroys itself, leaving behind the version that was brought back from scene 2 which does have the updated value that was changed within scene 2. But that would also require that my static Instance variable was only referencing the original when I returned to scene 1, making the reference null once that original gets destroyed… otherwise the other singleton (which came back from scene 2) would also destroy itself because it would run that check 2nd, see that Instance was not null, and destroy itself.
This all leads me to believe that I am wrong somewhere in my assumptions here. What am I misunderstanding?