Unity Singleton Pattern Clarification

Hi,

I’d just like to make sure I understand this correctly. Given that Unity manages the object lifecycle for you, the only way to create a singleton is to allow new instances to be created, but have them immediately destroy themselves? That seems potentially wasteful of resources.

I suppose my question is: are there other mechanisms of instance management commonly used in Unity that do not involve creating the object before assessing whether it needed to exist in the first place?

The Singleton is only instantiated and then destroyed if you do one of two things:

  • drop one into a scene in the editor, when one should already exist
  • call the constructor in code, rather than getting a reference to the static Instance

The Singleton pattern exists to safeguard against the first one, and if you do the second you’re not using your Singleton as designed.

Hope that makes sense, further reading here which I found really interesting (buy the book!).

Well, it appears also that if you leave and reenter a scene, you get new instances of all the objects. At least from what I see from GetInstanceId. But point taken, this is more about safeguarding than true instance management I’ve seen in other contexts.

Thanks for the resource, I’ll definitely have to look through more of the patterns there; the discussion around the strengths and pitfalls of singletons in general is already quite familiar to me. A cozy reread.