How does the Unity wiki Singleton work?

I have a GameObject "manager" in my scene with a Manager

Script component attached to it .

I need this Manager

Script to be a singleton as there is no point in having multiple managers in there.

I used the singleton implementation from the Unity wiki page.

I have two questions:

  • Why does it create a new GameObject and then use it GameObject.AddComponent<T>()

    to instantiate a singleton? Why not just do it new T()

    ?
  • I have protected

    both of my class constructors Singleton

    and Manager

    . Nobody should be able to create these classes other than themselves. How does the Unity editor do to create them?
+3


source to share


1 answer


As the comments say:

Exclusive classes cannot be set using new T()

because of the way GameObject components work: they must be attached to the GameObject! So the GameObject class provides a way to create a new MonoBehaviour attached to this GameObject: AddComponent<T>()

that supposedly works through reflection (other MonoBehaviour methods like Start()

and are Update()

n't exactly called with reflection , not every frame at runtime, but it's easy to make a comparison that they are, it's about opaque and magical, and has significant overhead, so it might well be a reflection).



Preventing the constructor from getting called at all would probably just break everything, so don't bother trying to protect it more than you already are. Because of the way AddComponent works, by invoking the constructor through reflection, you cannot actually prevent the creation of a new instance, but you can find that it did and do something about it. My preferred way is a script going "oh, the instance already exists and its not me" and destroys itself.

Also, since components may need other components (RigidBody requires a collider, MonoBehaviours can also specify its own requirements , which is specified via attributes, when AddComponent<T>()

called to add one component, it will look for class attributes to see if there is any [RequireComponents]

specified and add them automatically too, this will also be done through reflection .

+3


source







All Articles