Our Thoughts on Using Singletons in Unity

Sdílet
Vložit
  • čas přidán 25. 11. 2019
  • Sign up for the Level 2 Game Dev Newsletter: eepurl.com/gGb8eP
    This is a clip from my Game Development live stream. You can watch the whole stream at • Infallible Code - Unit...
    👨💻 Join our community: / discord
    ❤️ Support the channel: / infalliblecode
    My Favorite Unity Assets 💯⤵️
    1️⃣ Odin Inspector: assetstore.unity.com/packages...
    2️⃣ Shapes: assetstore.unity.com/packages...
    3️⃣ Easy Save: assetstore.unity.com/packages...
    4️⃣ Dialogue System for Unity: assetstore.unity.com/packages...
    5️⃣ Editor Console Pro: assetstore.unity.com/packages...
    ⚡ Learn more about Unity 3D Plus at prf.hn/click/camref:1100l3e8M/...
    👋 Contact me directly at charles@infalliblecode.com
    * Disclosure: These are affiliate links, which means I'll receive a commission if you use them to make a purchase.

Komentáře • 40

  • @jbmgil
    @jbmgil Před 2 měsíci

    That's the best explanation of the Singleton pattern concept applied to games that I've seen so far.

  • @mauriciopartnoy2789
    @mauriciopartnoy2789 Před 2 lety +3

    Im laughing out loud! The example you gave about having an audio manager and switching to FMOD happened to me once. Line by line. xD At least it made me more mindful about code architechture.

  • @gabagpereira
    @gabagpereira Před 2 lety +11

    Use Scriptable Objects instead! They work wonders and are easy to track and reference.

  • @Luis-Torres
    @Luis-Torres Před 4 lety +12

    I was sooo surprised by this video! For a while I've only ever used a singleton for my Gamemanager instance, because that makes sense to me. And then I hear some people say that Singletons are "bad" which confused me, because I can't imagine implementing a Gamemanager that manages the state of my entire game differently.
    Little did I know that the reason people speak so terribly about singletons is because, so many Unity developers try to use it so terribly! :O
    Not to make anyone here who has tried this sound stupid, but it never made sense to me to make the player a singleton or really anything else as specific as a the player inventory a singleton. To me the only place in Unity to write a Singleton is to handle the state of your game, which can be done through a GameManager instance.

  • @ChrysusTV
    @ChrysusTV Před 2 lety +1

    It's covered pretty well in the first 30 seconds. If you're using a singleton for something that isn't a scene-agnostic manager, you're probably doing something wrong. It isn't until using Unity that I've seen developers use singletons for something that, anywhere else in object-oriented programming, would be handled by a factory, store, controller, etc.

  • @toadill
    @toadill Před 4 lety +14

    I'm still lost without seeing code to represent it. If I can't do it myself after the explanation I feel like I'm at a loss.

    • @gcxs
      @gcxs Před 3 lety

      a singleton is like a global variable

  • @cnfnbcn3227
    @cnfnbcn3227 Před rokem +1

    It was some fallout I believe with the player-vehicle

  • @guardianoftheledge4966

    After watching this video I did the vehicle on character head hack. I just told the ai that it wasn't allowed to strafe and it could only turn and move forward/back. Worked great for my purposes haha.

  • @Layarion
    @Layarion Před 2 lety

    Can you guys cover how to make your Unity game moddable? and in the most flexible way. Like, can I somehow allow modders the same tools i use? like letting them use Unity for modding.

  • @dimarcinho
    @dimarcinho Před 4 lety

    Is there a way to continuous play a music between scenes without using a singleton?

  • @aldigangster123
    @aldigangster123 Před 3 lety +5

    I keep hearing that Singleton pattern is something to avoid over and over again. I understand why. But what are proper solutions to this? I'm researching how to manage game state over different scenes a couple of days now and can't find a tutorial of a "clean" way. Is additive scene loading the solution? Using a "State" scene being loaded as first, which contains all game manager gameObjects? And then additively load "Main Menu" scene, "Level 1", etc. on it? All Prefabs like the Player Prefab which are instantiated again in each different level, having the reference to the "State" scene's manager already in them - so they can save/load their data on/from it? It's driving me mad :)

    • @kickbass3441
      @kickbass3441 Před 3 lety +11

      I like jason's stance in this video. Instead of avoiding the singleton, use it on manager scripts. It makes perfect sense. You still get to keep ONE set of data and states, and you also have the flexibility of getting multiple actors pulling instructions from that manager.

  • @puretrack06
    @puretrack06 Před 4 lety +7

    I think the game is fall out 3 I know it is a Bethesda game

    • @puretrack06
      @puretrack06 Před 4 lety

      @antimech search fallout 3 train hat. The presidential metro train in Fallout 3 broken steel DLC is a hat on top of a human model

  • @alexkhazov7264
    @alexkhazov7264 Před 4 lety +4

    I noticed that your videos are quite quiet compared to other creators. Would it be possible to increase the volume in the future?

    • @ironbard4901
      @ironbard4901 Před 2 lety +2

      Hard disagree. On my end the audio is perfect.

    • @mehmetakyuz5290
      @mehmetakyuz5290 Před 2 lety +2

      @@ironbard4901 His voice is not balanced with the other guy 100%, saying that from my professional studio speakers.

  • @hiTocopter
    @hiTocopter Před 4 lety +7

    I feel like this discussion is making a mountain out of a molehill.
    The point of a singleton is that you should only have one. If, in this case, the Awake() function does delete an instance, you are doing something incorrectly (you are trying to instantiate another instance while there already is one = not intended functionality). Throw an exception, write an error-log, do something when that happens. Sometimes, it's too much of a hassle to work around trying to create another instance, so you'll live with the error-logging, but it should still be there. No one ever said a singleton should just accept being re-instantiated and overwritten smoothly.
    tl;dr: just add a Debug.LogError() if you are destroying/overwriting an instance in a singleton = problem solved.

  • @nocultist7050
    @nocultist7050 Před 3 lety

    Fallout 3 trains.

  • @JoeBlow-nu8yo
    @JoeBlow-nu8yo Před 9 měsíci

    Jason storey

  • @bvryahia1388
    @bvryahia1388 Před 2 lety

    Hi what if i use SingltonBinder some thing like this
    [DefaultExecutionOrder(-100)]
    public class SingltonBinder : MonoBehaviour
    {
    [SerializeField]
    Singltion []singlton;
    void Awake() {
    singlton = FindObjectsOfType();
    for(int i=0;i

  • @takenserious4554
    @takenserious4554 Před 2 lety

    My takeaway from this: If you're asking someone when you should or should not use a Singleton, then you should simply avoid using Singletons for now.

  • @r1pfake521
    @r1pfake521 Před 4 lety +26

    There are way too many Unity CZcamsr who teach people about bad singletons and they don't bother to research/explain better alternatives just because it was "easier" to use the singleton.
    I saw a RPG tutorial by a "famous" Unity CZcamsr who used singletons for almost everything.
    Your player needs a reference to the inventory? Easy just make the inventory a singleton with a public static property.
    Your quest system needs a reference to the player? Easy just make the player a singleton with a public static property.
    Your enemy needs a reference to the quest system? Easy just make... no, stop!
    These kind of "tutorials" make me vomit.

    • @IvisibleCat
      @IvisibleCat Před 4 lety +2

      can you explain in some words whats the problem about doing what you described, thanks.

    • @razveck
      @razveck Před 4 lety +6

      ​@@IvisibleCat They went over it in the video: what if you want to duplicate the player for some reason? Another one that's specific to Unity: is your Singleton a MonoBehaviour? If yes, do you do DontDestroyOnLoad()? If so, it will live in a separate scene forever. Are you calling other things from it? Will it try to change an object in the scene after that scene was unloaded? What about event subscriptions, are you making sure they are always cleaned up? What about asynchronous code? If you let it be destroyed, then when a scene is unloaded the Instance reference will be null. What if something in another scene references it?
      The problem that R1PFake mentioned with these tutorials is that 99% of the time they have very very limited scope. Sure, it's fine to make your Inventory a Singleton when your game is literally one scene and you don't save game state between plays, there is no multiplayer, etc. And don't get me wrong, I think tutorials that get people up and running with unity are great, but they also often teach them bad habits. Because for the tutorial's scope those things are irrelevant. For a real project, though, you will 100% shoot yourself in the foot (speaking from experience): in a complex project you cannot always be certain of the order in which things happen, or what might happen 1 year down the line when your Singleton is creating all sorts of problems but your codebase is already completely built on top of those Singletons? A project of any significance needs to have modular and flexible code that can be changed with minimal friction.

    • @ashfid8987
      @ashfid8987 Před 4 lety +3

      I am really thinking its Inscope Studios. I couldn’t watch it anymore. Sure, I will use singleton if I want to quickly prototype something. But I will either wrap it in a generic static function if it is frequently used or use events and delegates for it (which is much more better option)
      Singletons are fine if you want to hold database of objects or something. Just databases. But for everything, you are right. I felt like vomitting on that series. Though, he is a great teacher.

    • @R3lik101
      @R3lik101 Před 4 lety

      All that stuff sounds dangerous indeed. Why not just inject a component in the inspector. This is especially easy for communication between small amounts of objects.
      You can also separate smaller pieces of the data into their own ScriptableObjects and inject those. That way, you get the benefit of not having to rely on the player to exist for your prefabs. Other modular stuff is also potentially possible with SOs.
      Because i'm a beginner, can anyone validate what I just said?

    • @klarnorbert
      @klarnorbert Před 4 lety +2

      Using Singletons other than for Manager classes(SceneManager, GameManager, etc) or utility classes is just a bad idea. And lazy.

  • @michabiegaj1612
    @michabiegaj1612 Před 4 lety

    I can't agree with this movie. If you assume you have ONE PLAYER you shouldn't think "what if not". There won't be a situation like it. Of course, you can "cheat", but also you can block this behaviour by throwing an exception if the new singleton object is creating. That's funny because in c# you can literally make "sss" equal "ddd" if you make enough effort., but you still assume "sss" is "sss" hmmm. In a big project, I can't imagine myself always referencing to the player, especially when the player is not always in scene, because for example, he is spawning when a game is starting. Alternative? Yes, you can make
    "manager" but it is useless effort and make your code less readable and also doesn't fix the problem when you don't have the player on your scene. If you don't wanna use the player in any other way it is just a waste of time, and this is not solving problems which singleton has.
    I am gonna say more. Go decompile some unity games. I bet almost everyone is using singletons. I checked it out in Cuphead. Of course, the player is Unity singleton (Why shouldn't it be?).

    • @saniel2748
      @saniel2748 Před 3 lety +1

      That's interesting. How Player can be a singleton in cuphead if there are 2 players possible?

    • @michabiegaj1612
      @michabiegaj1612 Před 3 lety

      ​@@saniel2748 you're right, i guess i had to mistake the player with other class. Despite that fact, cuphead still have a lot of unity singletons in the code

    • @vanjazed7021
      @vanjazed7021 Před 2 lety

      In any Software field you can find people using sIngletons but majority of developers will tell you it should not be abused. Global mutable state, especially shared between threads, overall needs to be used very sparingly.
      The point is you should not abandon any usage of Singletons but you should only use it for things that make sense, not just polute everything with unnecessary side effects.
      In my opinion player specifically should just be treated as another entity. If you absolutely need easy access to it from anywhere you can cheat a little and provide direct access via your entity manager through some cached property. But you would be better off creating logic that can be applied as generally as possible to entities and pass player's entity to it as an argument. And then directly access player via high level scripts.

  • @hasnainfareed8555
    @hasnainfareed8555 Před 3 lety +1

    I am sorry to say, but your smile sometimes look quite sarcastic , like You are a proud person bullying some one.

    • @JasonStorey
      @JasonStorey Před 3 lety +9

      You are not the first person to tell me that, I apologize, it is not on purpose. Any half smile you spot is a bit of personal nostalgia. I have been studying and working with software architecture for 11 years which means I have... 11 years of mistakes.
      Any time I get a question, I am usually reminded of when I said exactly the same thing, or times I made mistakes that are now funny in retrospect.
      The only thing that is certain about somebody that "knows something" is that at one stage... they didn't.
      I would never look down on someone for not knowing something. I wouldn't spend my evening and weekends making educational content just to feel proud.
      I get paid to consult and contract. I could exclusively 'bully' people AND get paid for it.
      Instead though, I love learning. I spent my life cutting grass/fixing computers to earn enough money to get an hour long bus into town with 45 floppydisks in my hand to pay to use an internet cafe and download tutorials.
      Tutorials in everything from origami to cleaning ovens with a lemon.
      I owe a lot of my life to the power of free educational material and video tutorials on youtube (and the cool interactive flash ones on newgrounds).
      Truthfully part of it is that I am uncomfortable on camera. I have a bad habit of avoiding to look at the camera and it makes me look shifty. There is a lot about presenting myself on camera I have to practice.
      I guess I am still learning.

    • @hasnainfareed8555
      @hasnainfareed8555 Před 3 lety

      @@JasonStorey Sir
      Firstly,I pointed Mr.Charles's smile,not yours,You seem to be a humble guy
      Secondly I am a fan of your knowledge,after watching a few tutorials ,I searched for you , after a lot of search, I found that webpage of yours where you work.
      Thirdly Words you spoke here are Gold,and after listening to your story,my heart wept with tears , almost all the greats pass through this test . My Father has a similar story ,from being a homeless guy He became a big officer.
      Your knowledge speaks for your greatness, Hail
      I just wanted to be a personal student of yours,but obviously you must be a very busy guy ,thats why i dont want to tease you.