Search Unity

How does Unity wiki's Singleton work?

Discussion in 'Scripting' started by GuiTeK, Apr 28, 2017.

  1. GuiTeK

    GuiTeK

    Joined:
    Apr 28, 2017
    Posts:
    12
    Hi,

    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 has no sense to have several managers.

    I use the singleton implementation from the Unity wiki: Singleton - Unity3D Wiki

    I have two questions about it:
    1. Why does it create a new GameObject and then use GameObject.AddComponent<T>() to instanciate the singleton? Why not just do new T() ?
    2. I have protected both of my Singleton and Manager class constructors. No one should be able to instanciate these classes except themselves. How does the Unity Editor do to instanciate them?

    Thank you!
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Because you can't "new" MonoBehaviours; they are designed only to be attached to a GameObject. While you can make a non-MonoBehaviour singleton, there's not a lot of advantage to that over a simple static class (while MonoBehaviour-based singletons allow you to drag-n-drop assign members, get Update(), can run coroutines, etc).

    By the same token, a MonoBehaviour's constructor is pretty pointless; use Awake/Start for initialization. If you need to create one with parameters, make a static method that creates & attaches it to a GameObject, then returns the created instance.

    I don't think it's possible to prevent other classes from instantiating the class, but you can check in Awake if one already exists, and if so, destroy the new one.
     
    GuiTeK likes this.
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Incidentally, the code on the wiki page - like most of the code on the wildly unmaintained wiki, sadly - is really old (doesn't take advantage of generics, for example) and fairly inefficient (multiple FindObjectsOfType calls...?). I wrote my own implementation of the pattern here, which I would suggest is a better starting point than the one on the wiki.
     
    GuiTeK likes this.