Search Unity

Singleton beginner help

Discussion in 'Scripting' started by unity992, Feb 15, 2018.

  1. unity992

    unity992

    Joined:
    Jan 24, 2018
    Posts:
    44
    Why do we use singleton in game manager?i know that we can only create 1 instance in singleton and there is only one game manager.that is why we use singleton.but why is it bad to have multiple instances of game manager?
     
  2. ihgyug

    ihgyug

    Joined:
    Aug 5, 2017
    Posts:
    194
    The most basic example I think is when you have a Music Manager object with an AudioSource.
    You obviously want only a single MusicManager object per scene, and not multiple since then you would have multiple soundtracks playing at the same time.
    So let's say you have a menu and 2 levels, level 1 and level 2.
    From the menu you can access one of this 2 levels, and you want the music from level 1 to keep on playing when you move to level 2 and not start from the beginning again. And at the same time, you obviously want a Music Manager also in the level 2, in the case you access it directly from the menu and not from the level 1.
    What you do, is set the Music Manager on both scenes, and when you move from level 1 to 2, destroy the new Music Manager. That way you have a music that keeps on playing.

    In the case of a Game Manager, could be for tons of reasons. For example, lives, coins, whatever.
     
  3. jheiling

    jheiling

    Joined:
    Sep 28, 2010
    Posts:
    65
    Usually you will need just one instance of a game manager. But you never know... that's why singletons are considered an anti-pattern.
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    It isn't bad to have multiple game managers.

    It's that you've defined game manager as only having one existing. So you then used singleton to enforce this definition you gave it.

    As was pointed out... this actually could be bad if you poorly defined your situation. If it turns out that you need more game managers. But that depends on your design.

    If you only need one, because that's the way you want it, then singleton is perfectly fine for its needs.

    It always comes down to what YOU want to do as a developer.