Search Unity

What's the best way to make singletons?

Discussion in 'Scripting' started by KrisTheCoolGuy, Jan 7, 2022.

  1. KrisTheCoolGuy

    KrisTheCoolGuy

    Joined:
    Feb 16, 2020
    Posts:
    10
    has the title says, i'm curios if there's better way to create singletons in unity, i had found old post forums from like 2018-2019, if someone can help me about fining a good way to do so i would be happy :D
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Simple Singleton (UnitySingleton):

    Some super-simple Singleton examples to take and modify:

    Simple Unity3D Singleton (no predefined data):

    https://gist.github.com/kurtdekker/775bb97614047072f7004d6fb9ccce30

    Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

    https://gist.github.com/kurtdekker/2f07be6f6a844cf82110fc42a774a625

    These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

    If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

    Code (csharp):
    1. public void DestroyThyself()
    2. {
    3.    Destroy(gameObject);
    4.    Instance = null;    // because destroy doesn't happen until end of frame
    5. }
     
    KrisTheCoolGuy and GroZZleR like this.
  3. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Don't ;)
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    I know of the arguments against singletons, but do you want to elaborate on why not so that I know which arguments need to be shot down? All the anti-singleton arguments I've seen over the years come down to either "minor and esoteric use cases", or "right tool for the right job". Overall the benefits vastly outweigh drawbacks in Unity.
     
    orionsyndrome likes this.
  5. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    I think most of the legitimate arguments against Singletons don't really apply in game development (those being unit testing, maintenance, refactor difficulties, and bad juniors doing it wrong).

    Unless you're like making a library to distribute... then a service locator would be preferred. But even then, a service locator is just singleton with its best sunday dress.

    As for OP, @Kurt-Dekker pretty much answered the simple implementations of it. If you're looking for "best", well that gets subjective. Like I said, I prefer the service locator. But that isn't necessarily the "best", it's what I prefer.

    ...

    Back to the whole criticisms of singletons isn't really a gripe with a singleton, but rather as @StarManta put it, right to for the right place, argument. And that is some people overuse singletons and get themselves stuck in a corner. But this argument can be said of any pattern... it's not really the patterns fault, it's the developer not understanding their tools.

    But I mean honestly... the only way to learn how to use the singleton well is to... use it.
     
    Last edited: Jan 7, 2022
    CodeRonnie and TheTortilla like this.
  6. KrisTheCoolGuy

    KrisTheCoolGuy

    Joined:
    Feb 16, 2020
    Posts:
    10
    @Kurt-Dekker I'm curios about this part, this code can be placed in OnDestroy? sorry for my ignorance.

    Code (csharp):
    1. public void DestroyThyself()
    2. {
    3.    Destroy(gameObject);
    4.    Instance = null;    // because destroy doesn't happen until end of frame
    5. }
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    No, the code above is for when YOU want to end the life of the singleton, such as with a GameManager.

    Not all singletons live forever... you could call them something else in that case but most Unity developers just call them singletons. And the main point of MOST Unity singletons is to intentionally out-live the destruction when you change scenes. In general, a properly designed Unity singleton, even if it gets regenerated after a DestroyThyself() call above, will never allow more than one to be alive at once.
     
    Last edited: Jan 8, 2022
    Bunny83 likes this.
  8. jmcompany

    jmcompany

    Joined:
    Dec 24, 2017
    Posts:
    1
    public class Singleton : monobehaviour{
    public static Singleton instance;

    private void Awake(){
    instance = this;
    }
    }
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Apart and aside from your failure to a) use code tags, b) properly capitalize MonoBehaviour, and c) properly control access to the static instance field, the above tiny code fragment will also:

    - NOT survive a scene change
    - nor will it prevent multiple instances of itself existing
    - nor will it come into existence without being placed in the scene.

    So ... thanks?!
     
  10. Trey3Mtz

    Trey3Mtz

    Joined:
    Nov 15, 2023
    Posts:
    1
    What exactly do you mean when you say "predefined data"? Especially in the context of a unity game, what is considered "predefined data"?
     
  11. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    They mean data assigned in the editor/inspector.

    Basically the example linked creates the singleton lazily when the 'Instance' property is accessed. Since it's done this way that means there isn't a configurable instance of it in a scene to modify. Thusly there is no "predefined data" on the script.
     
    Kurt-Dekker and spiney199 like this.
  12. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,935
    Just any data you have prepared ahead of time. Aka, scriptable object, or a prefab, as per their description.
     
    Trey3Mtz and Kurt-Dekker like this.