Why a singleton without static _instance variable?

Hello there!

I know singletons from Java and other languages. And I know that there is a big discussion about pro and cons of singletons.

I would like to know why we created a singleton without a static _instance variable (some could argue that it’s not a singleton, it just happens to be instantiated once).
Is it faster in Unity doing it like in this lecture? Was it done because it should be as understandable as possible and therefore this was the better choice compared to static variables?

Just thinking about adding a CharacterManager in my game where you can select more than one character which is than set to be the active one. I thought about doing the CharacterManager as a Singleton and don’t know if it’s better doing it like Ben did.

Thanks!

I think mainly he was just showing you an alternate way of doing a Singleton. (It is a singleton, btw, the core of any singleton pattern is ensuring that there is never more than one copy, which this pattern accompllishes).

I’ve used both methods quite liberally, and here’s my general advice of when and where to use them…

  • Case 1: You just need a one off, destroy yourself if one already exists, because of persistence between scenes… This FindObjectOfType<>() method is more than sufficient. Note that if you place two players in the scene at edit time, this method will NOT work, both will destroy themselves.
  • Case 2: You need to access a CharacterManager from multiple classes… the classic _instance singleton is more appropriate for this.

Thanks for your answer!

According to the gang of four the constructor needs to be private for a Singleton (if I remember correctly) :wink:
As I said there could be lots of ppl who would discuss that. I don’t care to be honest.

I also would like to use the classical Singleton but I was just being curious if there is something I am missing.

Privacy & Terms