Reputation: 1731
I have a "manager" GameObject in my scene with a Manager
Script component attached to it.
I need this Manager
script to be a singleton since it makes no sense for there to be several managers.
I used the singleton implementation from the Unity wiki.
I have two questions about it:
GameObject.AddComponent<T>()
to instantiate the singleton? Why not just do new T()
?protected
both of my Singleton
and Manager
class constructors. No one should be able to instantiate these classes except themselves. How does the Unity Editor do to instantiate them?Upvotes: 3
Views: 445
Reputation: 15941
As the comments say:
MonoBehaviour classes cannot be instanciated with new T()
because of the way GameObject components work: they must be attached to a GameObject! As such, the GameObject class provides a way of instantiating a new MonoBehaviour attached to that GameObject: AddComponent<T>()
which presumably operates through reflection (other MonoBehaviour methods such as Start()
and Update()
aren't exactly invoked with reflection, not every frame during runtime, but it's easy to make the comparison that they are; it's about as opaque and magical and has significant overhead, so it may as well be reflection).
Preventing the constructor from being called at all would probably just break everything, so don't bother trying to protect it any more than you already are. Because of the way AddComponent works, calling the constructor through reflection, you can't actually prevent a new instance from being created, but you CAN detect that it happened and do something about. My preferred way is the script going "oh, an instance already exists and its not me" and destroys itself.
Additionally, as components can require other components (RigidBody requires a Collider, MonoBehaviours can specify their own requirements as well) which is specified through an attributes, when AddComponent<T>()
is called to add the one component, it will search the class attributes to see if there are any [RequireComponents]
specified and add them too, automatically. This would also be done through reflection.
Upvotes: 3