I like the "singleton" architecture and use it extensively in my game. Why I like it: 1. I like to be able to easily access all data, 2. I don't like to declare a Start() method in every single class just so I can get a reference to a class I use in 99% of the classes, 3. For me, the code is better organized this way. What I do is to create a monobehavior instance: Game.i and I use it to initialize the whole game, store references to all relevant classes, create, load and save GameInstance, that I access by Game.i.gameInstance, I also store general params like bool debug, etc, the whole game is a single scene, that I load and unload as I go. I store all the game resource data in Game.i.data, so I can access all the resources by the Game.i singleton. A more code-compact solution would be to turn the Data into a static class and create a LoadData method to load the resources references to the Data class, but I'm happy with this architecture now, because If In the future I decide to create a new scene, for a new game mode, (ie multiplayer), I can just not include any of the classes that aren't going to be used in the new mode and save a bit of memory.
One thing that I don't like about singletons is that when newer developers use them, they cause a few problems: highly linked code, unclear code responsibilities, spaghetti, removal of a single way to modify a data point, and other bad code smells. Are there valid places to use singletons, yes. Should they be avoided, yes. Also, I have found that in unity, for most situations were someone would use a singleton, you can use a scriptable object and have an instance of that that you wire up between the different objects that need to be able to interact with it. This gets you most/all of the benefits of singleton and allows you to get around most of the singleton issues (at least in terms of a Unity game, doesn't solve some of the scalability issues with multiple devices running your system). So, when I see a singleton come up when someone is asking for technical help, it almost always has a bunch of the other code smells that makes figuring out the code, etc much harder then it would be in a less coupled system. So basically, they seem to make other poor coding choices more common.
I agree with the fact that if your choice of using a singleton is for the sole purpose of global access, you should try to replace it with a ScriptableObject.
"code smells" is just snobbery of people who talk more about code then making anything useful coding. What matters is what the code is doing, and if it is performant, the design pattern is largely irrelevant. It's just subjective, like politics.
@@sdfsdfs13 I work with code constantly.. and code smells made working with code take way longer then without, make harder to fix bugs, all sorts of things. Sure if you're working on a sub 1-2k lines of code project, you might not need to care. But when you're working on 100+k lines of code projects that you didn't write (or wrote 12 months ago), you're going to want to be working on clean code
@@sdfsdfs13 Design patterns are for people that care about maintaining a clean codebase, making extensible components and systems that can be modified during the lifetime of the project without breaking everything with each new feature.
Thank you!!! I've been using singletons just like this, but every now and then, I encounter people utterly shaming me for even considering the use of singletons. I listen to them, but often go back to singletons (100% in a way you describe here). Low key feeling bad, like I'm a bad developer. **** that! You're right in saying there's seriously no reason what so ever for this to be controversial.
Hey Jason: interesting topic perhaps to others, too: okay, so everyone learns how to make a game in a sample scene - more or less. You wind up with a camera, player, UI and some more stuff. But how do you scale from there? How do you develop level 2, map 3, and zone 4? How does one keep the “level” apart from the stuff that is mostly the same across the game (player, camera etc). (1) is the core stuff a prefab (or several) in each scene? (2) use dontdestroyonload, effectively putting this in an auto multi-scene? (3) a multiscene setup, where the “global” stuff is in one scene and the level content is loaded in addition and swapped around? (4) some code that bootstaps everything into existence? (5) ??? Something on this would be amazing.
I've been a professional developer for a few years. Been getting into Unity recently. I'm self-taught so I've used loads of online courses, youtube videos, books, etc. I know how to learn coding fairly well and as I get more professional experience I've learned to appreciate and enjoy code philosophy. I feel compelled to say that this is easily my favorite source that I've come across, esp for the philosophy part which extends outside of unity or even c# more generally. Just chill, laid back, you aren't being 'extra' for the camera. Its like being able to sit down with a senior dev and get some wisdom at the click of a thumbnail. Subbed and clicked the bell. Looking forward to following!
Hey jason, i wanted let you know that i like how your videos are not editted every sentance with every clip zooming in and out. Also the lack of music. These 2 things are extremely distracting and doubly so when done wrong. Keep up the good work. Great topics,I am learning a bunch. :-)
I write Spring and Flink applications for a living and do game development on the side as a hobby. Spring is largely built on singletons. With constructor injection, they are very easy to unit test. If using good design patterns and interfaces, they can be very flexible and extendable. With that being said, I only sometimes use singletons in my Unity projects because the focus on scriptable objects / monobehaviors / scenes and their lifecycles.
I use the following code snippit for my cross-scene data, It typically goes in Awake(): DontDestroyOnLoad(this); if (Instance == null) { Instance = this; } else { Destroy(this); } keeps the instance of the object persistent, and gives you a way to access the script without the bog and limitations of static tags. Lastly, it destroys any extra copies that might get loaded during scene initializations, etc... if you need multiple instances than your going to have to build something more sophisticated, hence the argument that it is less scale-able.
First of all - nice video. I love singeltons - I don't like global access. There's a difference between instancing a single instance of a class and accessing it globally through GetInstance() method. Usually I like doing DI for singeltons because it eliminates the usage of a global access method and keeps me uncoupled to specific implementations or factory patterns. The most common usage of a singelton global access pattern is a log manager class: Actually using DI for all the ILog interfaces can create lots of junk in the code so usually a global instance is used to manage the log instances and appenders. This brings to another concept called - Aspect oriented programming which tries to decouple such facilities from the core behavior of the application. The need for decoupled components isn't just "You won't implement another Inventory system" - it's to decouple the components to analyze bugs quicker and maintain your code faster. On large scale projects the sooner you get to decoupling the better.
There are definitely arguments against singletons and I rarely use. them outside Unity. But specifically for Unity they're very handy. I typically use them as hubs with no actual logic in the singleton itself or for dontdestroyonload objects to avoid creating a second instance when reentering the scene
In enterprise we use singleton alot too. We leverage a DI container to make them testable and let the DI container make instances singleton. This way a test can overwrite the instance with mocks. I try to use them just like you explained. Great Video! Like most patterns you have to know when to use what.
I've just bit the bullet and started learning Godot and as soon as the tutorials said you needed to use singletons to store values between scenes Jason popped up in his miniature office in my head
It works both ways...most people atleast here at comment section usually just blindly support or are against stuff like singletons without having any meaningful knowledge or experience on the matter. Best practice is to think of comment section as entertainment and videos as pointer to a subject you should research
Two things that I often do when I'd previously use a singleton have the getting method in another class and return an interface instead of a concrete implementation which kinda goes against the singleton pattern but it does allow you to have the option to change the implementation if you need to without having to do a big rewrite And I currently haven't found many disadvantages with it
I think a good note to add is that it gets less confusing if all of the methods that alter singleton values/states lie within the singleton as opposed to a bunch of other scripts.
I only use singletons if I want to ensure there's only one object of a class ever available, this is what the pattern was originally intended for anyways. As opposed to "I'm lazy and I cba finding the correct reference so I'm just going to make everything statically available". On top of this I've settled upon the rule that singletons are only allowed when there's one-way-traffic. As in, I manipulate a variable or call a method but don't retrieve any data from the singleton. I would agree on making loggers, soundmanagers, toasts or other utility-esque classes singletons because they are usually called and then let go. Making the player a singleton is a hard disagree for me. The argument of "I know its going to be a singleplayer game" is also the counterargument: because of your pattern you've made it inextensible to ever become multiplayer. I feel that's a poor decision because you have no reason to use singleton (I think) other than being lazy. I get it though. I was formally educated as a software engineer with a strong sense for architecture. I made the switch to Unity about 5 years ago and most terms like OOP, loose-coupling and extensibility are lost on the average Unity developer as it's usually not at all needed. But I ended up working for an infrastructure company that creates 'serious games' without a strongly defined scope (meaning the customer suddenly decides they want multiplayer 4 months into the project) and my seemingly inane drive to keep my enterprise-programming principles within Unity is paying off. No offense to anyone but I really feel like Jason Weimann knows what he's talking about but then hundreds of people join in on the comments and it becomes a mess of a discussion. All in all, my advice is to steer clear of using singletons unless you need them. You probably need them less often than you think. And the reason why you should steer clear of them is not because they are inherently bad. The reason is because I can tell the difference between a CS student and a gamedev student by looking at their code and so can your future coworkers if you ever choose to venture into other programming positions.
I love singletons! I have like 20 in my current scene! It eases a lot the reference pain! And it's very useful for things that I'm sure won't need a double, now or one day!
So in my case I created an SO that grabs the players Data after the first time the player comes into being.The player has the Base class and it's inherited player class but the Base class on Start runs a Setup sequence with overarching game logic, the base class (which every character including npcs inherit from) on update checks first if the Game Manager is Setup and then populates the SO with data if the SO Instance isn't already initialized. After that the SO is given a unique ID initially, this I just grab the GameObject ID built into Unity since those are random anyway. So now when I run the game the data persists for everything. To be clear though, the initial stats on the Base characters are each clones of other SO's unique to each base character. My idea is that the data on the base is easy to save vs saving the SO so when I do a save I get the runtime data on the SO to inform the values on the base class then save the base class. On load the base class checks if the SO data is different and if so updates the SO info. What are the benefits of this? Probably nothing, it just makes it so I can pull the SO information when I don't need the player or something enemy directly in the scene. I am experimenting with it though and honestly just doing the stats directly on the base character may be better. Ah with that said, I'm not sure if I've ever thought to make my player a Singleton, in my mind the player is a Controller type not a Manager type. But I can see why it could be a Manager. The things I think of as manager are: Game Manager, Scene Manager, UI Manager, Dungeon (Spawn) Manager, World (Quests/Events) Manager, Sound Manager and finally my Pool Manager. The Pool Manager has several pool controllers under it, some more generalized pools, some specific ones like projectiles. But it is handling the references to them. What I wanted to learn more about was persistent scene Managers. I don't see many YT videos about it if any.
Some audio tips for your videos: you should remove that noise gate from your audio track, the only thing it's doing is cutting off the starts of all words after a short silence. You've also got the gain a bit too high on the mic, your voice is distorting a little bit on the louder words. Try using a compressor to make your voice louder! It kinda bugs me which is a shame because your content is always really great!
I put singletons in the same category as switch statements: an elegant expression of a often-but-not-always flawed way of thinking. Singletons typically facilitate code architecture that can be visualized as a hub-and-spokes--the singleton is the central hub and all the things it interacts with are the spokes. The benefit of this model is that anything can easily access anything else without exponential cross references via common reference to the hub...and this is also the drawback. For if everything is connected then everything is mutually dependent and you lose all hope of modularity. The key thing to note here, however, is that the underlying issue is the underlying hub-and-spokes model, using a singleton is a mere implementation detail. In fact, if one conceives of their problem space along the lines of that analogy, I would much rather they do so with singletons rather than make some other crazy indirect process with all plus more of the drawbacks and none of the benefits. The biggest disagreement I have with the video is actually not (directly) related to singletons. Specifically, the claim that because games are typically not software-as-a-service you don't need to worry much about architecture in the sense of being modular and reusable. Sure, the trade-off might not make sense in the context of a single project, but the reusable code libraries a programmer or studio builds up to leverage in future projects is a major potential competitive advantage--and, in an even broader sense, the fundamental reason why technology becomes more advanced over time. Sure, most of the time "totally general" solutions reveal themselves to be useless once the context changes, but then you figure out why, learn from the mistake, and write something better the next time until one more aspect of the job becomes automated away and you can focus on other things. Like the saying (I just made up) goes: "refactoring never makes sense to management, sometimes makes sense for a project, and always makes sense for the engineer" (meaning that the idea of investing time to "improve" something so it works the same is rather weird from the outside, is sometimes an economical investment and sometimes not, but always a valuable experience for learning/developing/improving).
Singletons are a powerful tool, as long never two singletons reference each other. Having a central singleton to request independent systems, which are then kept by reference is always fine.
Can be a scriptableObject or static class, static dictionary. No need for a singleton. There is zero advantage in using a Singleton to reference scene objects.
@@johnleorid Ehm, no, there are several advantages. First, a ScriptableObject has to be referenced somewhere in the first place, so you have to set it up in some way. Second, a dictionary falls short, as you usually have some parameter needs. And sorry, what else than a singleton is a static class? Only the dirty little sister of one. Seriously, talking against singletons and bringing up statics instead is a bit shady... A singleton is a structured way compared to your Wild West alternatives and in the end, you almost always need a central instance. Believe me, I‘m developing games and applications for nearly 40 years now, and a singleton is a structured way to have a central backbone in the program. Sure, you rarely need more than one and they should never ever reference each other. But beside that, using a singleton solves a lot of problems, especially with Unity, when scene changes come into place. And - being too dogmatic about a pattern is not a healthy world view... Nobody forces you to use them.
@@bremstrk5641 If you are required to stay in the Unity serialization pipe, they are the same. Or one can say, you can't have static classes in the sense you mention it here, if you prefer this perspective.
@@SunSailor ScriptableObject can be a singleton. So you don't need to set it up in the inspector. In fact I find it even more powerful, because you can access the scriptable object singleton everywhere, because it's not a game object, as opposed to regular monobehaviour singletons where you need to have an instance in the scene in some way.
I'm still learning and I've noticed I've been using singletons quite a bit too much, but still don't know how to avoid it, it's simply too convenient having all these "control rooms". My game has a UIManager (contains a reference to every canvas so I can enable/disable them when needed), a QuestManager (keeps track of all quests on the scene to trigger stuff), an InputManager (gets inputs, duh), a GameStateManager (to manage scene loading) and a GameManager (holds public lists of all actors on the scene), as well as an NPCFactory (for the spawners to use); all of them singletons. They're all relatively small and very specific; two managers never reference each other but still I want to find ways to avoid it.
@@aaronschneider1581 It feels lazy and uninspired, but I don't really know how to do better for now so I'm not gonna touch it until I know what am doing.
I'm in the exactly same boat and works fine, but I would like to know alternatives of avoid them(if is possible without tight things in other way), I have searched a lot and not find some unity architecture to follow, I didn't want to, but I'll go with zenject
I'm a professional programmer who's worked at several game studios. Currently a Lead Programmer working on games for all consoles. Here's the thing, having one instance of a thing is fine. The issue with Singletons specifically, is they combine that with global access. Do you really need global access to QuestManager or UIManager (also side note, naming everything Manager really goes against the whole point of OOP. Objects are supposed to take care of themselves. Do you really need a Manager for everything?) That's what coupling is, hard references to other classes. Now if you make a change to QuestManager that can easily break other seemingly unrelated systems because you have this connection of Singletons to Singletons. It's extremely easy to create spaghetti code with singletons, which are VERY hard to debug, thus costing us more time and MONEY TO FIX. Full stop that is reason alone to not use them, they are very easy to write bad code with and it costs us developement time to fix later when issue inevitably arise. An alternative in a OOP language is using dependency injection. That is you pass any dependcies a class has thru the constructor. However, if you are using Unity, and specifically writing classes that inherit form Monobehaviour, they hide the constructor so you can't do that. I dislike Unity for many reasons, this being one of them. Alternative would be either don't use Monobehaviours if you truly don't need them. Does QuestManager really need to exist on a gameobject in 3d space or can it just be code that runs outside of the scene? Or if they absolutely need to be Monobehaviours, Create a public Initialize() whose parameters are the dependencies you need to work with. I'm not an OOP fanboy, but people should learn to use their tools correctly. Working as a professional this really does matter as it often takes more time and money to fix. Seriously, I do this for a living. Bad code makes debugging really hard, which makes fixing bugs hard, which means timelines often get pushed back, which means we lose money or have to work overtime to fix. TL:DR: Singletons on their own are fine. However they make it extremely easy to write bad code and bad code should be avoided as much as possible. This is a good resource on good programming patterns for games. gameprogrammingpatterns.com/
I love using singletons for my Office VSTO Add-ins (off topic from video games, for sure). Any time I create a new button group in Excel, for example, I'll have a singleton that manages that group of buttons and anything in the code can reference it at any time. It also always for multiple documents to be open and interact with that one instance instead of multiple instances being created for each workbook I have open.
Before this video I thought you spent 15 years in game development and only ever knew singleton pattern. I'm glad that's not the case! The only reason I use Singletons is for development purposes when I'm working on several scenes and I don't necessarily start play mode in one which has a system, so I drop the system to all the scenes and let Singleton logic prevent duplicates. Everything else is event driven programming, parent-child relationships and some utility classes. You covered singleton pros very well but they do not outweight the cons in my opinion.
I’ve found it helpful to hide the implementation of a singleton (or any subsystem for that matter) behind an interface. Combine that with some dependency injection can make for a flexible system. Can make it a lot easier for mocks and stubs in testing.
@@thatoneuser8600 Absolutely... until you need it. Definitely keep it simple to start with - but it's worth thinking how you would extend if needed to minimise refactoring.
I had a friend in elementary school name Josh Singleton, bout 30 years ago I would say. I always wonder what that old dude is up to, be hilarious if he was a computer programmer. I honestly only use Singletons for managers, and I don't use many managers because I feel like that is "too many cooks in the kitchen" for me.
Great explanation. Exactly, most games don't need that much extensibility, that's why it's perfectly fine to use singletons here. There's a lot of places where you only need one instance of some kind of manager and singletons really shine there. There are a lot of places where it is better not to use singletons, but not using them at all is not an ideal solution either
in my racing game, Singleton i use i think is only int for cars and int for tracks, when start driving(soon racing/othe rgame mode) it chekks quickly what (int) car and What (int) Track, my quick simpel dirty way of starts with correct car on correct track, downside is that i had to also code so that if am working on 1track and play test is spawn defaul car hehe :D Great video as allways :D
Hi, I am one of the guys who maybe not hate the Singleton but I see that Singletons are used in a very bad way, I also have pretty strict opinions on singletons. I believe a singleton should not contain more than one state, eg. ScoreSingleton should only contain the score nothing else. This will lead to a lot of Singletons and that is not good. Let's assume you have a PlayerSingleton containing the information about the player; score, location, weapons, health, stamina etc. Then assume your player get into game over and wants to replay the game, now you need to reset all these values to avoid bugs like starting with wrong weapons, wrong location or even starting with the previous games ending score. These are some of the most common bugs I have seen, especially among new developers. If you instead of making your Inventory into a singleton you make an InventoryFactory that is a singleton that will only have one state, the instance of your Inventory, this makes the InventoryFactory singleton very small having only one state that needs to be restored and that can be done by just create a new Inventory instance within the reset function of your InventoryFactory. No chance you will forget to restore anything. Doing this InventoryFactory a Singleton will also help you with the tests, in your tests you can create as many Inventory as you like without the InventoryFactory making sure you know the state of the class you are testing. It also scales if needed and you can extend if you want as well with small effort.
Hi Jason! I love you videos, and your face!! somehow this zooming in and out of the camera and all the stuff/lights in the background makes it a little bit distracting, i wish there was a bit less of it so it is easier to focus on your face and what you are saying... :) Thanks Jason!:)
I can see all sides to this discussion, but nothing beats the feeling of just opening a scene and testing an object with several components ready to go. It's important that they work independently of monolithic objects that would need to always be in the scene in case you had used Singletons instead of smarter patterns However, for a single-scene throwaway prototyping project, sure, I use Singletons all the time
In web apis singletons are strongly recommended for repos and http clients. All classes should be injected with interfaces for testability with exceptions such as mappers and dtos. Try instantiating an http client for each request and you will run out of network sockets.
Thanks for this video. The anti-singleton crowd are extremely emotional and irrational about them, like radical religious people who see them as "The Devil". I see no cognitive difference between conservative christians in the south screeching about how evil Harry Potter is and "Programmers" who screech about how evil Singletons are. It's the same weird emotional rage and inability to just chill. Their argument is always this worst-case-scenario strawman. This newbie programmer who makes literally everything a Singleton. I dont believe these people exist and even if they did, it's stupid to assume they must be taught to avoid Singletons. Someone who grossly misuses a programming tool will misuse EVERYTHING. Avoiding singletons will NOT somehow stop their incompetence. If you understand a tool, you can use it. But religiousity (irrational, emotional tribalism) always exists in every group. Singletons, Globals, Engine Wars, etc. The irony is that most video games are poorly programmed. Some violate gamedev 101 like Bethesda games. Hell, Bethesda's ESO MMORPG is apparently programmed by engineers who have absolutely no understanding of even novice programming. Reading their problems in their update blogs are so frighteningly embarassing. You're talkimg about mistakes even novices wouldn't make. Skyrim ties physics to framerate which is one of the first things modern game programmers learn to NOT do. Northgard are on reddit saying saving data in multiplayer is technologically "Impossible". No lie - they go multiple posts saying it's not possible to save a multiplayer game. Go look it up. A few uses of singleton isnt the end of the world, but there exist those anti-singleton types - quite a lot of them - who will mock, rage, and attack people for even saying singletons arent always evil. And Logic is like oxygen for Programmers, so I am confident these religious types are not very bright. It's one thing to not use the tool for reasons, but it's an entirely different thing to be evangelical about how bad they are. It's scary to know just how much that religious tribalism has infected the brains of so many people who are suppose to be logical like a Vulkan.
If you are doing a small game is usually fine, but if the project grows a lot you are likely to face some of the typical singleton problems: cross-references, events that remains in limbo. I learned this the hard way.
All you have to do is keep in mind what your singletons are doing (you shouldn't have so many you cant keep track of them) and when the project begins entering the danger zone or you run into or predict problems soon, REFRACTOR. But you dont have to refractor until you get there. Like optimization, you may never get there.
One other design problem of singletons : you can't use inheritance. I find it the most frustrating thing when you try to extract some components onto self contained packages. To add on the "Keep it Simple", I will advise to avoid cross referencing singletons and try to avoid keeping too much state in them.
I agree with a lot of this. The way I've found singletons maximize helpfullness while minimizing pain is to treat singletons as kind of "One way" entities between the layers of your game. So if I have a manager singleton that game objects can talk up to, that singleton shouldn't talk back down to the game objects. It's okay if maybe it goes over and talks to the UI component, but this way you don't have these weird chains of functions that revolve in going back and forth to a singleton, and you can kind of easily stub out the singleton functions if you are setting up testing.
i like to use my game manager as singleton. Because my game manager is like a dungeon master of d&d soo it must be one and easy to reach that also have guidance to other stuffs i need. Also depend on game logic i can turn my player script into singleton alongside with game manager but currently just keeping game manager as singleton solve all my desires XD
I’ve started to get to a work flow where I use singletons but don’t directly reference them. Instead I use static classes that pass data through events to the singletons, and the singletons have callback functions. It’s an extra layer so it’s more work, but it decouples the code so that things don’t break when you remove the singletons. For my purposes I have yet to see why not to work this way.
I'm making a single-player / local co-op adventure game. And in our game, I have a prefab that's just called "SceneRequirements" that contains singletons, UI, and the main characters that are required for every single level. I've never had any issues with this whatosever. I plop it in the scene, press play, and I don't have to ask any more questions than that. Is it tightly coupled? Some systems are yes. However... I can see zero instances where any of the objects in SceneRequirements wouldn't be in a level in the game. Maybe I'll be proven wrong in the future, but not yet!
You can do a Singleton factory instead of a singleton of your object. This will give the same result but it will be easier to scale, maintain, test and extend if needed.
I've seen many ads for Skill Share and in like every one the videos themselves look to be like 5 minutes or less (e.g. 1:19). Not sure how I feel about that; I mean maybe you guys are super smart, but I don't like seeing new skills taught in a few minutes. I mean that ain't gonna be enough time for me to learn something new, unless it was super simple. I see in the 2D course Jason showed in the intro, the "Photoshop basics" chapter is 25 minutes. That's reasonable. I just see so many chapters like 2 or 3 minutes and think "that ain't enough for me."
Hey man, I am coming from web development, I am using singletons as an injection tool in my singleplayer game, like I have 10-15 different managers as a game objects and in place of passing them to each object which uses them, I just pass them into singleton and call them out from there. This way when I add CharacterCombat script to a 100th instance of a player, I don't need to insert again AudioManager, DayNightCycleManager or whatever is needed. Any opinions on that?
idk if other folks felt this, but the camera panning was a bit distracting in this video. It didn't feel like it was connected to anything Jason was saying, which might've been unnecessary ^^"
Literally everything in the comments and everything about singletons boils down to: "Is singleton the tool that I need to use to solve my problem? If yes, use singleton, if no, don't use singleton." I don't think people who randomly hate or dislike singletons for no reason actually understand why they should dislike them. You should dislike the "misuse" of singletons, when a different tool would have done a job in a proper way. If singleton were a hammer, you should dislike it when people use it as a screwdriver. You don't hate people having the tool in their toolbox or using it when it's appropriate.
Thank you for the video Jason. One thing that I still do not understand is what exactly is the benefit of using Singletons over regular Static methods in the same class? E.g. Instead of calling a method via SomeController.Instance.MyMethod(), why can't "MyMethod" simply be a static method inside the SomeController class that I can call like SomeController.MyMethod()?
@@TehMighty Why would you need non-static variables? The Singleton needs non-static variables because it is an instance. However, if there is only ever going to be a single instance, then functionally it works exactly the same as having a static class with static variables. So everything will be static. Which was basically my question - why do we have a Singleton instance with non-static variables instead of static class with static variables?
@@TehMighty I am actually not arguing at all. I am genuinely trying to understand what is the advantage of using Singletons instead of a static class. Because I am new to this stuff and do not understand it.
@@muhammadsaadali388 it really is all up to what you're doing and how you want it done. Static classes work for some things, but not for others. Singletons are stupid easy to get working with anything, but are easy to misuse. Static classes you might need to get around inheritance, polymorphism, etc, which there are ways to do it, but with Singletons you really just pop it in and use it. Which is the danger of them. They're extremely useful and so easy to implement anywhere you want, but it can create a "knot" of code down the line if you're not careful.
@@LeviAckerman-xt7dx u can, I like to use a scriptable object for my pools. It manages each pool, but I keep the data and management separate. ruclips.net/video/raQ3iHhE_Kk/видео.html&ab_channel=Unity Ryan Hipple gives a fun talk about scriptable objects.
Every tool has a place. A big part of the hate for singletons is that many developers fail to follow two rules 1. Begin with the end in sight and 2. Plan for success. For games, just ask yourself, what happens if this game does really well, what is the next step?
I think singletons should be not used in 2021, as there is a dependency injection. It's super simple to set up and super simple to use. Check out Zenject for Unity. It's just absurd that people still talk about singletons
For most games, it's actually stupid to NOT use singletons. And I am pretty sure Jason's last video on singletons mentioned how most games DO use them. I think a big problem is (just a guess) professors across universities or some author of a college book go out of their way to instill how evil they are to students. That, or it's common in companies for mentors or bosses to freak out if they're used. My theory is there's a culture of misunderstanding and Fear around some programming tools like Singletons. Those without independent thought or experience to know better just parrot what they're told. It becomes a cycle and cultural meme people take seriously. Odd, as we should all know that all programming tools exist for valid reasons. Otherwise they wouldn't exist and/or became obsolete.
It's a great tool if we don't misuse it and know when to draw a line. I think the problem why it is so controversial is because many inexperience programmers use it incorrectly and caused serious coupling.
I personally do not like singletons. The tl;dr version is that I come from a business background and I like to be economical with how I write code. You might not ever have to extend, test, or swap out code but having the option make for a happy programmers and happy non-programmers. No long unexpected slow down in development while you back track on code you can't extend, test, or swap out. And let's be honest, many projects have been killed by a bug that just couldn't be squashed in a timely manor. With that said, I think a case can be made for pretty much all programming patterns given the right circumstances.
I 100% agree with this especially if you work with anyone else you always want to give the option for extension, changing of implementation and testing I'm currently studying game programming and we've had 1-2 week projects were we have regretted not using extensible and abstract code. We've had to throw away a few days of work because of it and this as said was very short projects so I can't imagine how it would be in huge projects
I appreciate the video, but disagree with your reasoning generally. "I know it will be fine as a singleton" is really "I don't want to support having multiple instances." Usage of singletons is, by definition, limiting oneself and the possible features your game could support. I have also often found that usage of a singleton mindset leads to god classes that end up doing everything. Forcing yourself to solve a given problem without using singletons often teaches you how to better structure your game, avoiding problems later.
I'm not a fan of singletons because I really dislike the idea of mixing the type of the object with the instance of the object itself, it doesn't sit well with me, but I get the appeal and how they are useful if done properly. I'm just happy with my ScriptableObject Pointers...
I really like Singletons that exist on a single scene and don't add the complexity of "DontDestroyOnLoad" that comes with some implementations. Just have the script hold a static reference to itself that's initialized in the start method. What about using unserialized non-monobehaviour classes? I've always thought Utility classes might be a good way to go but I hardly ever see it used by any Unity developers. Any thoughts?
I think it comes down to Unity callbacks. Some find very disturbing not having the usual callback loop like Start, Awake, Update, OnCollisionEnter, etc. When implementing manager classes, I rarely use these callbacks, so I guess, making a plain old C# singleton class is not a bad idea.
In the last year or so, I've come to the conclusion that there's a significant difference in the inherent value of singletons between game programming contexts and regular programming contexts. I started with Unity programming, and very often singletons seem to naturally fit in. Loading screen? Player manager? Game manager? All of these seemed almost destined to be singletons from the get-go. There would only be one instance for the game's run (Seriously, when exactly are you going to need two different uniquely functioning instances of a loading screen system?) and they need to maintain a certain state for their lifetime (I'd very much like to see a player manager that doesn't need to keep track of what inputs each player is operating). But later on, I decided I wanted to try creating some custom porting tools to help pull out data from other proprietary formats for use in Unity. This, I feel, is much closer to the usual enterprise or other "non-game" programming contexts. As it turns out, I wound up working with libraries primarily designed to be embedded into a game, so there were a few built-in singletons I needed to work with. And I very quickly realized that, for my purposes of "just read this proprietary file and return the data inside", the management of singletons and their life cycles suddenly became substantially more cumbersome (though not impossible). I wound up creating a static HashSet of streams and had to write up some checks that track how many streams are open and initializes or decommissions the singletons once that count leaves or hits zero. Again, not ridiculous, but significantly more awkward than in the game programming context of Unity, since these tools really shouldn't need any state to determine their function; if you need to both pull and drive nails, why would you constantly switch between a mallet and crowbar when you can just use a claw hammer? Bottom line, I think you really need to consider the context of your programming, because that will factor greatly into which patterns are or aren't useful. Just like a violinist has a much greater need for a bow than a harp player even though the violinist can still play by plucking strings, I believe game programming has a much greater need (or at the very least applicability) for singletons than enterprise programming even though statelessness still has plenty of uses for games.
Main problem I see is when they hold state that can be changed freely. Even with proper methods and hiding implementation details it can be a pain to track down why abd when something changed the global state of the singleton. It's also a static dependency which can't be changed easily or injected but you already touched that. If you're building a singleton that just contains references to other systems and provides easy access to those systems it's less problematic (UIManager f.eg.) but global state is really evil. If you have s script that's not intended for reuse go for the singleton because it's quick and dirty and gets the job done. When you need a layer of abstraction or need the class to be extendable or testable go for the mediator or similar event pattern. At least that's my goto.
Yeah, global state is a mess, but it's a really hard part to manage for new comers. In the past years I began to use scriptable objects instead of using singletons for state management, but it's not as easy as it sounds. Really, global state is a hard thing to get right.
@@soverain yeah you can really go wrong with singletons if you're not careful. They're can be extremely costly to refractor out, which is why I generally like to make dependencies explicit in Init methods or lookups in awake and cache as private fields. It's not as clean as enterprise dev with the whole DI-magic but it still works good enough to make stuff testable and isolated without the overhead of a full-fledged DI-framework. I also made a generic purpose mediator with strongly typed events which I abuse everywhere. Being able to follow events in code instead of trying to track down scriptableobject usages is a godsend for me and for testing, but I build stuff for myself not for a designer. Again if the static dependency is not a problem for the given behavior (it's not intended for reuse) slap that singleton on it. Only use the big tools when you need them for a specific purpose.
A lot of people talking about how singletons are bad in the comments, but based on 5 years of daily experience with Unity/Unity communities i know that at least 80% of these people is used to have a bad performant code like Find at runtime...
I think the Singleton pattern is not used by many programmers because the pattern doesn't give any real benefit. If you want to have one reference to something-- feel free to do so, but you shouldn't lock yourself behind that restriction. A lot of game development is about iteration and finding what feels good. Why limit your possibilities by using singletons? Re: performance; I'm not familiar with performance tests using singleton architecture in game projects-- but I'll take your word that it grants some minor benefit there.
@@umapessoa6051 There's some nuance here that you're missing. There is a difference between what is functionally a singleton -- and the design pattern of using singletons in object-oriented architecture. And while there’s nothing wrong with having only one instance of an object (the prior), using the “Singleton Pattern” (the latter) to achieve this is never the best solution. I won't go into the specifics here, but I'm talking more about what he mentioned regarding Enterprise applications. And he hit the nail on the head. Unity programming is different. You don't control a lot of the ways things are connected together on an architectural level, because it's handled by the engine. (And that's part of the benefit of using that engine, you can focus on the functions and not the architecture.)
There's a lot of different categories of "Singletons". I tried for a long time to never use them. Then I finally learned that you simply can't make a game without them. And if you do, you wasted a lot of time and confusion. Remember, when you finish a game, most of its code is thrown away, and only experience is retained. Don't try and write it like a corporate program meant to survive re-writes and extensions for the next 2 decades.
Novice programmers doesn't have clear understanding about building good software architecture so it's better to teach them that singletons are bad. When they became more experienced, they will learn use cases for singletons themselves. Until that, it's better to put effort into learning solid principles or other good practices rather than trying to defy singletons. For more experienced programmers singletons are not even a question. They can be justified in some cases, but these use cases are very limited. In general, many singletons in software is a sign of poor design decisions
It's awful you assume students are so incompetent. This demonization of a valid tool guarantees they are. Have a little hope ffs. Singletons are fine btw. Both for novices and experienced programmers. It's not so "limited" as you pretend. You're just someone who emotionally wants to demonize them bc your "tribe" demonizes them or you were taught to.
@@nowayjosedaniel But students are limited. Human without appropriate experience is limited. It will take few years to understand how to build good program architecture. It's not me demonizing singletons, it's hard-learned lessons from much more experienced programmers from years and years of practice
@@LSDemian Students are limited? Your argument was that the proper usage of singletons are Limited. I assume this is some ESL breakdown so I'll give you a pass here. Do these "experienced programmers" have more experience than Jason Weimann? Unlikely. Just stop dude. Singletons are fine. Just like all programming tools, they can be misused or abused. Nothing is safe, but you dont see people screaming about how novices should avoid C++ bc of memory leaks or how newbies shouldnt ever use While bc of infinite loops.
For those who wonder for a singleton replacement - take a look on a dependency injection frameworks. Zenject for unity is great, makes it easy to achieve same stuff as with singletons but with less drawbacks
@@LSDemian If you want people to accept a "Singleton replacement" you should start by actually making a real argument as to why they're never good. One that refutes Jason's arguments that they shouldn't be hated, since Jason makes a very strong argument to why they can be good. Otherwise, you're just saying "They're bad. Why? Because they're bad."
So singletons just sound like the lazy option, sure if you got the balls and just want to make sometinge small and fast. then I can see the use. But for everyting else not going with the right solution just sounds like the same argument for pirating a movie instead of bying it. or peeing you pants, like it feels good and hot in the moment but later its really gonna suck. but if you gonna change you pants or are in the public pool no problem :D
That was one of the worst explanations I have ever heard! Maybe try to simplify and speak to someone that doesn't know anything instead of speaking from within your own head, thoughts and experiences.
Nr of projects completely destroyed by using singletons: 99999999 Nr of projects harmed by not using them: 0 (by destroyed I mean that you can't add any feature without rewriting basically the entire game) IDK, I wouldn't risk it, even as experienced dev.
Singletons are controversial because people don't know how to use them. In other words, misinterpretation of singleton usage is why it's hated. Singletons are amazing.
@@umapessoa6051 It's like making a campfire in your kitchen to cook food instead of using the oven right next to it. Those things are dangerous, I've seen project which you could throw away entirely because of Singletons. And only because of Singletons, everything else was fine, commented code, variables with good names and so on. But yea, whatever, there are more than enough other Videos out there, warning people about Singletons... it's none of my business after all.
Jason Weimann - a AAA MMORPG expert game programmer with 15-20 years experience. Dmitriy Demian - "NEVER program like Jason Weimann." Idk who should we believe? Can you link your youtube channel or portfolio?
@@LSDemian Would love any example of how "player code is not something that should be accessible globally" could lead to problems instead of sounding like something you're parroting from a programming boomer, and I'm asking this as someone that strives to avoid singletons whenever possible
@@LSDemian How is it a personal attack to point out Jason Weimann knows what he is doing? He is a well known individual and an expert game programmer. Are you an expert game programmer? Show us your portfolio. Btw that isnt an attack to ask.
I use a pre-load scene and singletons at the same time to make sure that all communities hate me
Wait people are shitting on pre-load scenes now? What on earth for
@@vanilla-plus I don't think most people do if it is reasonable.
I like the "singleton" architecture and use it extensively in my game. Why I like it: 1. I like to be able to easily access all data, 2. I don't like to declare a Start() method in every single class just so I can get a reference to a class I use in 99% of the classes, 3. For me, the code is better organized this way. What I do is to create a monobehavior instance: Game.i and I use it to initialize the whole game, store references to all relevant classes, create, load and save GameInstance, that I access by Game.i.gameInstance, I also store general params like bool debug, etc, the whole game is a single scene, that I load and unload as I go. I store all the game resource data in Game.i.data, so I can access all the resources by the Game.i singleton. A more code-compact solution would be to turn the Data into a static class and create a LoadData method to load the resources references to the Data class, but I'm happy with this architecture now, because If In the future I decide to create a new scene, for a new game mode, (ie multiplayer), I can just not include any of the classes that aren't going to be used in the new mode and save a bit of memory.
One thing that I don't like about singletons is that when newer developers use them, they cause a few problems: highly linked code, unclear code responsibilities, spaghetti, removal of a single way to modify a data point, and other bad code smells.
Are there valid places to use singletons, yes. Should they be avoided, yes.
Also, I have found that in unity, for most situations were someone would use a singleton, you can use a scriptable object and have an instance of that that you wire up between the different objects that need to be able to interact with it. This gets you most/all of the benefits of singleton and allows you to get around most of the singleton issues (at least in terms of a Unity game, doesn't solve some of the scalability issues with multiple devices running your system).
So, when I see a singleton come up when someone is asking for technical help, it almost always has a bunch of the other code smells that makes figuring out the code, etc much harder then it would be in a less coupled system. So basically, they seem to make other poor coding choices more common.
I agree with the fact that if your choice of using a singleton is for the sole purpose of global access, you should try to replace it with a ScriptableObject.
"code smells" is just snobbery of people who talk more about code then making anything useful coding. What matters is what the code is doing, and if it is performant, the design pattern is largely irrelevant. It's just subjective, like politics.
@@sdfsdfs13 I work with code constantly.. and code smells made working with code take way longer then without, make harder to fix bugs, all sorts of things. Sure if you're working on a sub 1-2k lines of code project, you might not need to care. But when you're working on 100+k lines of code projects that you didn't write (or wrote 12 months ago), you're going to want to be working on clean code
@@sdfsdfs13 Design patterns are for people that care about maintaining a clean codebase, making extensible components and systems that can be modified during the lifetime of the project without breaking everything with each new feature.
Thank you!!! I've been using singletons just like this, but every now and then, I encounter people utterly shaming me for even considering the use of singletons. I listen to them, but often go back to singletons (100% in a way you describe here). Low key feeling bad, like I'm a bad developer.
**** that! You're right in saying there's seriously no reason what so ever for this to be controversial.
Hey Jason: interesting topic perhaps to others, too: okay, so everyone learns how to make a game in a sample scene - more or less.
You wind up with a camera, player, UI and some more stuff. But how do you scale from there? How do you develop level 2, map 3, and zone 4? How does one keep the “level” apart from the stuff that is mostly the same across the game (player, camera etc).
(1) is the core stuff a prefab (or several) in each scene?
(2) use dontdestroyonload, effectively putting this in an auto multi-scene?
(3) a multiscene setup, where the “global” stuff is in one scene and the level content is loaded in addition and swapped around?
(4) some code that bootstaps everything into existence?
(5) ???
Something on this would be amazing.
Was there anything ever made on this?
I was literally just looking up your singleton videos last night for some tips. Thanks.
I've been a professional developer for a few years. Been getting into Unity recently.
I'm self-taught so I've used loads of online courses, youtube videos, books, etc. I know how to learn coding fairly well and as I get more professional experience I've learned to appreciate and enjoy code philosophy.
I feel compelled to say that this is easily my favorite source that I've come across, esp for the philosophy part which extends outside of unity or even c# more generally.
Just chill, laid back, you aren't being 'extra' for the camera. Its like being able to sit down with a senior dev and get some wisdom at the click of a thumbnail.
Subbed and clicked the bell. Looking forward to following!
Hey jason, i wanted let you know that i like how your videos are not editted every sentance with every clip zooming in and out. Also the lack of music. These 2 things are extremely distracting and doubly so when done wrong. Keep up the good work. Great topics,I am learning a bunch. :-)
I write Spring and Flink applications for a living and do game development on the side as a hobby. Spring is largely built on singletons. With constructor injection, they are very easy to unit test. If using good design patterns and interfaces, they can be very flexible and extendable. With that being said, I only sometimes use singletons in my Unity projects because the focus on scriptable objects / monobehaviors / scenes and their lifecycles.
I use the following code snippit for my cross-scene data, It typically goes in Awake():
DontDestroyOnLoad(this);
if (Instance == null) { Instance = this; }
else { Destroy(this); }
keeps the instance of the object persistent, and gives you a way to access the script without the bog and limitations of static tags. Lastly, it destroys any extra copies that might get loaded during scene initializations, etc... if you need multiple instances than your going to have to build something more sophisticated, hence the argument that it is less scale-able.
First of all - nice video.
I love singeltons - I don't like global access.
There's a difference between instancing a single instance of a class and accessing it globally through GetInstance() method.
Usually I like doing DI for singeltons because it eliminates the usage of a global access method and keeps me uncoupled to specific implementations or factory patterns.
The most common usage of a singelton global access pattern is a log manager class:
Actually using DI for all the ILog interfaces can create lots of junk in the code so usually a global instance is used to manage the log instances and appenders.
This brings to another concept called - Aspect oriented programming which tries to decouple such facilities from the core behavior of the application.
The need for decoupled components isn't just "You won't implement another Inventory system" - it's to decouple the components to analyze bugs quicker and maintain your code faster.
On large scale projects the sooner you get to decoupling the better.
There are definitely arguments against singletons and I rarely use. them outside Unity. But specifically for Unity they're very handy.
I typically use them as hubs with no actual logic in the singleton itself or for dontdestroyonload objects to avoid creating a second instance when reentering the scene
In enterprise we use singleton alot too. We leverage a DI container to make them testable and let the DI container make instances singleton. This way a test can overwrite the instance with mocks.
I try to use them just like you explained. Great Video!
Like most patterns you have to know when to use what.
I've just bit the bullet and started learning Godot and as soon as the tutorials said you needed to use singletons to store values between scenes Jason popped up in his miniature office in my head
Very controversial topic, as far as I know ; ) Looking forward to this one! 👍🏻
My favorite part:
"Keep Singletons Simple".
With that and all the insults the anti-singleton crowd throw, maybe they should be renamed Simpletons? ;)
That's how I use my singletons and keep them readable.
Must use abstract class Simpleton - base singleton pattern in next game..
I honestly hate blanket statements like don't do "x" and so forth. There's a whole world of opportunities for the right price.
At least those people expose themselves as being close-minded/herd-driven so you know to factor that in when they give opinions, etc.
Don't use the 'streaming assets' folder. Also, don't stick your hand into hot molten lava.
It works both ways...most people atleast here at comment section usually just blindly support or are against stuff like singletons without having any meaningful knowledge or experience on the matter. Best practice is to think of comment section as entertainment and videos as pointer to a subject you should research
Two things that I often do when I'd previously use a singleton have the getting method in another class and return an interface instead of a concrete implementation which kinda goes against the singleton pattern but it does allow you to have the option to change the implementation if you need to without having to do a big rewrite
And I currently haven't found many disadvantages with it
I think a good note to add is that it gets less confusing if all of the methods that alter singleton values/states lie within the singleton as opposed to a bunch of other scripts.
Yeah, it should be like "never change a field directly from another script", state should be self-managed.
Nice lighting setup. Everything looks more contrasted.
I only use singletons if I want to ensure there's only one object of a class ever available, this is what the pattern was originally intended for anyways. As opposed to "I'm lazy and I cba finding the correct reference so I'm just going to make everything statically available". On top of this I've settled upon the rule that singletons are only allowed when there's one-way-traffic. As in, I manipulate a variable or call a method but don't retrieve any data from the singleton. I would agree on making loggers, soundmanagers, toasts or other utility-esque classes singletons because they are usually called and then let go. Making the player a singleton is a hard disagree for me. The argument of "I know its going to be a singleplayer game" is also the counterargument: because of your pattern you've made it inextensible to ever become multiplayer. I feel that's a poor decision because you have no reason to use singleton (I think) other than being lazy.
I get it though. I was formally educated as a software engineer with a strong sense for architecture. I made the switch to Unity about 5 years ago and most terms like OOP, loose-coupling and extensibility are lost on the average Unity developer as it's usually not at all needed. But I ended up working for an infrastructure company that creates 'serious games' without a strongly defined scope (meaning the customer suddenly decides they want multiplayer 4 months into the project) and my seemingly inane drive to keep my enterprise-programming principles within Unity is paying off.
No offense to anyone but I really feel like Jason Weimann knows what he's talking about but then hundreds of people join in on the comments and it becomes a mess of a discussion. All in all, my advice is to steer clear of using singletons unless you need them. You probably need them less often than you think. And the reason why you should steer clear of them is not because they are inherently bad. The reason is because I can tell the difference between a CS student and a gamedev student by looking at their code and so can your future coworkers if you ever choose to venture into other programming positions.
I love singletons! I have like 20 in my current scene! It eases a lot the reference pain! And it's very useful for things that I'm sure won't need a double, now or one day!
lol have you been cured of illness yet
So in my case I created an SO that grabs the players Data after the first time the player comes into being.The player has the Base class and it's inherited player class but the Base class on Start runs a Setup sequence with overarching game logic, the base class (which every character including npcs inherit from) on update checks first if the Game Manager is Setup and then populates the SO with data if the SO Instance isn't already initialized.
After that the SO is given a unique ID initially, this I just grab the GameObject ID built into Unity since those are random anyway. So now when I run the game the data persists for everything.
To be clear though, the initial stats on the Base characters are each clones of other SO's unique to each base character. My idea is that the data on the base is easy to save vs saving the SO so when I do a save I get the runtime data on the SO to inform the values on the base class then save the base class. On load the base class checks if the SO data is different and if so updates the SO info.
What are the benefits of this? Probably nothing, it just makes it so I can pull the SO information when I don't need the player or something enemy directly in the scene. I am experimenting with it though and honestly just doing the stats directly on the base character may be better.
Ah with that said, I'm not sure if I've ever thought to make my player a Singleton, in my mind the player is a Controller type not a Manager type. But I can see why it could be a Manager. The things I think of as manager are:
Game Manager, Scene Manager, UI Manager, Dungeon (Spawn) Manager, World (Quests/Events) Manager, Sound Manager and finally my Pool Manager.
The Pool Manager has several pool controllers under it, some more generalized pools, some specific ones like projectiles. But it is handling the references to them.
What I wanted to learn more about was persistent scene Managers. I don't see many YT videos about it if any.
Some audio tips for your videos: you should remove that noise gate from your audio track, the only thing it's doing is cutting off the starts of all words after a short silence. You've also got the gain a bit too high on the mic, your voice is distorting a little bit on the louder words. Try using a compressor to make your voice louder!
It kinda bugs me which is a shame because your content is always really great!
Glad to see i'm not the only one who finds the audio worst than before.
I put singletons in the same category as switch statements: an elegant expression of a often-but-not-always flawed way of thinking. Singletons typically facilitate code architecture that can be visualized as a hub-and-spokes--the singleton is the central hub and all the things it interacts with are the spokes. The benefit of this model is that anything can easily access anything else without exponential cross references via common reference to the hub...and this is also the drawback. For if everything is connected then everything is mutually dependent and you lose all hope of modularity. The key thing to note here, however, is that the underlying issue is the underlying hub-and-spokes model, using a singleton is a mere implementation detail. In fact, if one conceives of their problem space along the lines of that analogy, I would much rather they do so with singletons rather than make some other crazy indirect process with all plus more of the drawbacks and none of the benefits.
The biggest disagreement I have with the video is actually not (directly) related to singletons. Specifically, the claim that because games are typically not software-as-a-service you don't need to worry much about architecture in the sense of being modular and reusable. Sure, the trade-off might not make sense in the context of a single project, but the reusable code libraries a programmer or studio builds up to leverage in future projects is a major potential competitive advantage--and, in an even broader sense, the fundamental reason why technology becomes more advanced over time. Sure, most of the time "totally general" solutions reveal themselves to be useless once the context changes, but then you figure out why, learn from the mistake, and write something better the next time until one more aspect of the job becomes automated away and you can focus on other things. Like the saying (I just made up) goes: "refactoring never makes sense to management, sometimes makes sense for a project, and always makes sense for the engineer" (meaning that the idea of investing time to "improve" something so it works the same is rather weird from the outside, is sometimes an economical investment and sometimes not, but always a valuable experience for learning/developing/improving).
Singletons are a powerful tool, as long never two singletons reference each other. Having a central singleton to request independent systems, which are then kept by reference is always fine.
Can be a scriptableObject or static class, static dictionary. No need for a singleton.
There is zero advantage in using a Singleton to reference scene objects.
@@johnleorid Ehm, no, there are several advantages. First, a ScriptableObject has to be referenced somewhere in the first place, so you have to set it up in some way. Second, a dictionary falls short, as you usually have some parameter needs. And sorry, what else than a singleton is a static class? Only the dirty little sister of one. Seriously, talking against singletons and bringing up statics instead is a bit shady... A singleton is a structured way compared to your Wild West alternatives and in the end, you almost always need a central instance.
Believe me, I‘m developing games and applications for nearly 40 years now, and a singleton is a structured way to have a central backbone in the program. Sure, you rarely need more than one and they should never ever reference each other. But beside that, using a singleton solves a lot of problems, especially with Unity, when scene changes come into place.
And - being too dogmatic about a pattern is not a healthy world view... Nobody forces you to use them.
@@johnleorid wtf? isnt singletons already static classes. Also scriptableObject? really? that is dumb
@@bremstrk5641 If you are required to stay in the Unity serialization pipe, they are the same. Or one can say, you can't have static classes in the sense you mention it here, if you prefer this perspective.
@@SunSailor ScriptableObject can be a singleton. So you don't need to set it up in the inspector. In fact I find it even more powerful, because you can access the scriptable object singleton everywhere, because it's not a game object, as opposed to regular monobehaviour singletons where you need to have an instance in the scene in some way.
I'm still learning and I've noticed I've been using singletons quite a bit too much, but still don't know how to avoid it, it's simply too convenient having all these "control rooms". My game has a UIManager (contains a reference to every canvas so I can enable/disable them when needed), a QuestManager (keeps track of all quests on the scene to trigger stuff), an InputManager (gets inputs, duh), a GameStateManager (to manage scene loading) and a GameManager (holds public lists of all actors on the scene), as well as an NPCFactory (for the spawners to use); all of them singletons. They're all relatively small and very specific; two managers never reference each other but still I want to find ways to avoid it.
Why do you want to find ways to avoid it?
@@aaronschneider1581 It feels lazy and uninspired, but I don't really know how to do better for now so I'm not gonna touch it until I know what am doing.
I'm in the exactly same boat and works fine, but I would like to know alternatives of avoid them(if is possible without tight things in other way), I have searched a lot and not find some unity architecture to follow, I didn't want to, but I'll go with zenject
I'm a professional programmer who's worked at several game studios. Currently a Lead Programmer working on games for all consoles.
Here's the thing, having one instance of a thing is fine. The issue with Singletons specifically, is they combine that with global access. Do you really need global access to QuestManager or UIManager (also side note, naming everything Manager really goes against the whole point of OOP. Objects are supposed to take care of themselves. Do you really need a Manager for everything?)
That's what coupling is, hard references to other classes. Now if you make a change to QuestManager that can easily break other seemingly unrelated systems because you have this connection of Singletons to Singletons. It's extremely easy to create spaghetti code with singletons, which are VERY hard to debug, thus costing us more time and MONEY TO FIX. Full stop that is reason alone to not use them, they are very easy to write bad code with and it costs us developement time to fix later when issue inevitably arise.
An alternative in a OOP language is using dependency injection.
That is you pass any dependcies a class has thru the constructor. However, if you are using Unity, and specifically writing classes that inherit form Monobehaviour, they hide the constructor so you can't do that. I dislike Unity for many reasons, this being one of them.
Alternative would be either don't use Monobehaviours if you truly don't need them. Does QuestManager really need to exist on a gameobject in 3d space or can it just be code that runs outside of the scene?
Or if they absolutely need to be Monobehaviours, Create a public Initialize() whose parameters are the dependencies you need to work with.
I'm not an OOP fanboy, but people should learn to use their tools correctly. Working as a professional this really does matter as it often takes more time and money to fix. Seriously, I do this for a living. Bad code makes debugging really hard, which makes fixing bugs hard, which means timelines often get pushed back, which means we lose money or have to work overtime to fix.
TL:DR:
Singletons on their own are fine. However they make it extremely easy to write bad code and bad code should be avoided as much as possible.
This is a good resource on good programming patterns for games.
gameprogrammingpatterns.com/
I love using singletons for my Office VSTO Add-ins (off topic from video games, for sure). Any time I create a new button group in Excel, for example, I'll have a singleton that manages that group of buttons and anything in the code can reference it at any time. It also always for multiple documents to be open and interact with that one instance instead of multiple instances being created for each workbook I have open.
Before this video I thought you spent 15 years in game development and only ever knew singleton pattern. I'm glad that's not the case!
The only reason I use Singletons is for development purposes when I'm working on several scenes and I don't necessarily start play mode in one which has a system, so I drop the system to all the scenes and let Singleton logic prevent duplicates. Everything else is event driven programming, parent-child relationships and some utility classes.
You covered singleton pros very well but they do not outweight the cons in my opinion.
I’ve found it helpful to hide the implementation of a singleton (or any subsystem for that matter) behind an interface. Combine that with some dependency injection can make for a flexible system. Can make it a lot easier for mocks and stubs in testing.
YAGNI: You aren't gonna need it.
@@thatoneuser8600 Absolutely... until you need it. Definitely keep it simple to start with - but it's worth thinking how you would extend if needed to minimise refactoring.
I had a friend in elementary school name Josh Singleton, bout 30 years ago I would say. I always wonder what
that old dude is up to, be hilarious if he was a computer programmer.
I honestly only use Singletons for managers, and I don't use many managers because I feel like that is "too many cooks in the kitchen"
for me.
Great explanation.
Exactly, most games don't need that much extensibility, that's why it's perfectly fine to use singletons here. There's a lot of places where you only need one instance of some kind of manager and singletons really shine there.
There are a lot of places where it is better not to use singletons, but not using them at all is not an ideal solution either
in my racing game, Singleton i use i think is only int for cars and int for tracks, when start driving(soon racing/othe rgame mode) it chekks quickly what (int) car and What (int) Track, my quick simpel dirty way of starts with correct car on correct track, downside is that i had to also code so that if am working on 1track and play test is spawn defaul car hehe :D
Great video as allways :D
Hi, I am one of the guys who maybe not hate the Singleton but I see that Singletons are used in a very bad way, I also have pretty strict opinions on singletons. I believe a singleton should not contain more than one state, eg. ScoreSingleton should only contain the score nothing else. This will lead to a lot of Singletons and that is not good.
Let's assume you have a PlayerSingleton containing the information about the player; score, location, weapons, health, stamina etc. Then assume your player get into game over and wants to replay the game, now you need to reset all these values to avoid bugs like starting with wrong weapons, wrong location or even starting with the previous games ending score. These are some of the most common bugs I have seen, especially among new developers.
If you instead of making your Inventory into a singleton you make an InventoryFactory that is a singleton that will only have one state, the instance of your Inventory, this makes the InventoryFactory singleton very small having only one state that needs to be restored and that can be done by just create a new Inventory instance within the reset function of your InventoryFactory. No chance you will forget to restore anything.
Doing this InventoryFactory a Singleton will also help you with the tests, in your tests you can create as many Inventory as you like without the InventoryFactory making sure you know the state of the class you are testing.
It also scales if needed and you can extend if you want as well with small effort.
Thanks Jason, you're always a pleasure to listen to. I wonder if SkillShare has a course on using unicode in credit rolls? :D
More Arquitecture stuff yaaay :D
Hi Jason!
I love you videos, and your face!!
somehow this zooming in and out of the camera and all the stuff/lights in the background makes it a little bit distracting, i wish there was a bit less of it so it is easier to focus on your face and what you are saying... :)
Thanks Jason!:)
I can see all sides to this discussion, but nothing beats the feeling of just opening a scene and testing an object with several components ready to go. It's important that they work independently of monolithic objects that would need to always be in the scene in case you had used Singletons instead of smarter patterns
However, for a single-scene throwaway prototyping project, sure, I use Singletons all the time
In web apis singletons are strongly recommended for repos and http clients. All classes should be injected with interfaces for testability with exceptions such as mappers and dtos. Try instantiating an http client for each request and you will run out of network sockets.
Hope he provides some best practices concerning singletons (MonoBehaviour or otherwise)!
I try at least a bit in this video, explaining the uses that I've found to work well :)
Thanks for this video.
The anti-singleton crowd are extremely emotional and irrational about them, like radical religious people who see them as "The Devil". I see no cognitive difference between conservative christians in the south screeching about how evil Harry Potter is and "Programmers" who screech about how evil Singletons are. It's the same weird emotional rage and inability to just chill.
Their argument is always this worst-case-scenario strawman. This newbie programmer who makes literally everything a Singleton. I dont believe these people exist and even if they did, it's stupid to assume they must be taught to avoid Singletons. Someone who grossly misuses a programming tool will misuse EVERYTHING. Avoiding singletons will NOT somehow stop their incompetence.
If you understand a tool, you can use it.
But religiousity (irrational, emotional tribalism) always exists in every group. Singletons, Globals, Engine Wars, etc.
The irony is that most video games are poorly programmed. Some violate gamedev 101 like Bethesda games. Hell, Bethesda's ESO MMORPG is apparently programmed by engineers who have absolutely no understanding of even novice programming. Reading their problems in their update blogs are so frighteningly embarassing. You're talkimg about mistakes even novices wouldn't make. Skyrim ties physics to framerate which is one of the first things modern game programmers learn to NOT do. Northgard are on reddit saying saving data in multiplayer is technologically "Impossible". No lie - they go multiple posts saying it's not possible to save a multiplayer game. Go look it up.
A few uses of singleton isnt the end of the world, but there exist those anti-singleton types - quite a lot of them - who will mock, rage, and attack people for even saying singletons arent always evil.
And Logic is like oxygen for Programmers, so I am confident these religious types are not very bright. It's one thing to not use the tool for reasons, but it's an entirely different thing to be evangelical about how bad they are. It's scary to know just how much that religious tribalism has infected the brains of so many people who are suppose to be logical like a Vulkan.
Ultimately, people want their tribe to be considered "right", because that gives the tribe social power, actual objective correctness be damned.
If you are doing a small game is usually fine, but if the project grows a lot you are likely to face some of the typical singleton problems: cross-references, events that remains in limbo. I learned this the hard way.
All you have to do is keep in mind what your singletons are doing (you shouldn't have so many you cant keep track of them) and when the project begins entering the danger zone or you run into or predict problems soon, REFRACTOR.
But you dont have to refractor until you get there. Like optimization, you may never get there.
One other design problem of singletons : you can't use inheritance. I find it the most frustrating thing when you try to extract some components onto self contained packages.
To add on the "Keep it Simple", I will advise to avoid cross referencing singletons and try to avoid keeping too much state in them.
I agree with a lot of this. The way I've found singletons maximize helpfullness while minimizing pain is to treat singletons as kind of "One way" entities between the layers of your game. So if I have a manager singleton that game objects can talk up to, that singleton shouldn't talk back down to the game objects. It's okay if maybe it goes over and talks to the UI component, but this way you don't have these weird chains of functions that revolve in going back and forth to a singleton, and you can kind of easily stub out the singleton functions if you are setting up testing.
i like to use my game manager as singleton. Because my game manager is like a dungeon master of d&d soo it must be one and easy to reach that also have guidance to other stuffs i need.
Also depend on game logic i can turn my player script into singleton alongside with game manager but currently just keeping game manager as singleton solve all my desires XD
Thank you Jason !
I’ve started to get to a work flow where I use singletons but don’t directly reference them. Instead I use static classes that pass data through events to the singletons, and the singletons have callback functions. It’s an extra layer so it’s more work, but it decouples the code so that things don’t break when you remove the singletons. For my purposes I have yet to see why not to work this way.
With great power comes great responsibility.
Awesome! Thanks for the video! Really helped me learn when to and when not to use singletons!
We inject singletons via interface with the help of Zenject. Thus we keep them testable and replaceable.
I'm making a single-player / local co-op adventure game. And in our game, I have a prefab that's just called "SceneRequirements" that contains singletons, UI, and the main characters that are required for every single level. I've never had any issues with this whatosever. I plop it in the scene, press play, and I don't have to ask any more questions than that. Is it tightly coupled? Some systems are yes. However... I can see zero instances where any of the objects in SceneRequirements wouldn't be in a level in the game. Maybe I'll be proven wrong in the future, but not yet!
Sorry for the off topic question. Why you have a box with “DONT OPEN”?
Can you please make a video on easy to learn singleton alternatives?
You can do a Singleton factory instead of a singleton of your object. This will give the same result but it will be easier to scale, maintain, test and extend if needed.
I've seen many ads for Skill Share and in like every one the videos themselves look to be like 5 minutes or less (e.g. 1:19). Not sure how I feel about that; I mean maybe you guys are super smart, but I don't like seeing new skills taught in a few minutes. I mean that ain't gonna be enough time for me to learn something new, unless it was super simple.
I see in the 2D course Jason showed in the intro, the "Photoshop basics" chapter is 25 minutes. That's reasonable. I just see so many chapters like 2 or 3 minutes and think "that ain't enough for me."
I'll study in deep about singleton after I finish the alpha version of my game or even just finished and study for the next projects.
Hey man, I am coming from web development, I am using singletons as an injection tool in my singleplayer game,
like I have 10-15 different managers as a game objects and in place of passing them to each object which uses them, I just pass them into singleton and call them out from there.
This way when I add CharacterCombat script to a 100th instance of a player, I don't need to insert again AudioManager, DayNightCycleManager or whatever is needed.
Any opinions on that?
Don't give me this 'right tool for the right job' crap - Jason vs Ryan Hipple tonight in the shatterdome. Butterfly knives only.
idk if other folks felt this, but the camera panning was a bit distracting in this video. It didn't feel like it was connected to anything Jason was saying, which might've been unnecessary ^^"
Literally everything in the comments and everything about singletons boils down to: "Is singleton the tool that I need to use to solve my problem? If yes, use singleton, if no, don't use singleton."
I don't think people who randomly hate or dislike singletons for no reason actually understand why they should dislike them. You should dislike the "misuse" of singletons, when a different tool would have done a job in a proper way.
If singleton were a hammer, you should dislike it when people use it as a screwdriver. You don't hate people having the tool in their toolbox or using it when it's appropriate.
Thank you for the video Jason. One thing that I still do not understand is what exactly is the benefit of using Singletons over regular Static methods in the same class? E.g. Instead of calling a method via SomeController.Instance.MyMethod(), why can't "MyMethod" simply be a static method inside the SomeController class that I can call like SomeController.MyMethod()?
Referencing non static variables, for one.
@@TehMighty Why would you need non-static variables? The Singleton needs non-static variables because it is an instance. However, if there is only ever going to be a single instance, then functionally it works exactly the same as having a static class with static variables. So everything will be static. Which was basically my question - why do we have a Singleton instance with non-static variables instead of static class with static variables?
@@muhammadsaadali388 Then you're just arguing semantics and preference, and there literally is no point in arguing that.
@@TehMighty I am actually not arguing at all. I am genuinely trying to understand what is the advantage of using Singletons instead of a static class. Because I am new to this stuff and do not understand it.
@@muhammadsaadali388 it really is all up to what you're doing and how you want it done.
Static classes work for some things, but not for others. Singletons are stupid easy to get working with anything, but are easy to misuse.
Static classes you might need to get around inheritance, polymorphism, etc, which there are ways to do it, but with Singletons you really just pop it in and use it. Which is the danger of them.
They're extremely useful and so easy to implement anywhere you want, but it can create a "knot" of code down the line if you're not careful.
Scripatble Objects are my singletons
Lol how about the manager classes? You also do them on scriptable objects?
@@LeviAckerman-xt7dx u can, I like to use a scriptable object for my pools. It manages each pool, but I keep the data and management separate.
ruclips.net/video/raQ3iHhE_Kk/видео.html&ab_channel=Unity
Ryan Hipple gives a fun talk about scriptable objects.
@@dustypants9326 yep ur right I'm currently watching it's now. It's magical.
Odd bit of serendipity this - currently in the process of refactoring a bunch of singleton patterns out of my game.
I really want to open that box
What's the alternative that others use? Scriptable objects?
Every tool has a place. A big part of the hate for singletons is that many developers fail to follow two rules 1. Begin with the end in sight and 2. Plan for success. For games, just ask yourself, what happens if this game does really well, what is the next step?
I think singletons should be not used in 2021, as there is a dependency injection. It's super simple to set up and super simple to use. Check out Zenject for Unity. It's just absurd that people still talk about singletons
I like to have multiple instances of my singletons, because I like being myself.
We use singletons all the time. They are good
For most games, it's actually stupid to NOT use singletons. And I am pretty sure Jason's last video on singletons mentioned how most games DO use them.
I think a big problem is (just a guess) professors across universities or some author of a college book go out of their way to instill how evil they are to students. That, or it's common in companies for mentors or bosses to freak out if they're used. My theory is there's a culture of misunderstanding and Fear around some programming tools like Singletons. Those without independent thought or experience to know better just parrot what they're told. It becomes a cycle and cultural meme people take seriously.
Odd, as we should all know that all programming tools exist for valid reasons. Otherwise they wouldn't exist and/or became obsolete.
It's a great tool if we don't misuse it and know when to draw a line. I think the problem why it is so controversial is because many inexperience programmers use it incorrectly and caused serious coupling.
I personally do not like singletons. The tl;dr version is that I come from a business background and I like to be economical with how I write code. You might not ever have to extend, test, or swap out code but having the option make for a happy programmers and happy non-programmers. No long unexpected slow down in development while you back track on code you can't extend, test, or swap out. And let's be honest, many projects have been killed by a bug that just couldn't be squashed in a timely manor. With that said, I think a case can be made for pretty much all programming patterns given the right circumstances.
I 100% agree with this especially if you work with anyone else you always want to give the option for extension, changing of implementation and testing
I'm currently studying game programming and we've had 1-2 week projects were we have regretted not using extensible and abstract code. We've had to throw away a few days of work because of it and this as said was very short projects so I can't imagine how it would be in huge projects
Singleton: there can be only one!
Born to be Kings!
I appreciate the video, but disagree with your reasoning generally. "I know it will be fine as a singleton" is really "I don't want to support having multiple instances." Usage of singletons is, by definition, limiting oneself and the possible features your game could support. I have also often found that usage of a singleton mindset leads to god classes that end up doing everything. Forcing yourself to solve a given problem without using singletons often teaches you how to better structure your game, avoiding problems later.
I'm not a fan of singletons because I really dislike the idea of mixing the type of the object with the instance of the object itself, it doesn't sit well with me, but I get the appeal and how they are useful if done properly. I'm just happy with my ScriptableObject Pointers...
I really like Singletons that exist on a single scene and don't add the complexity of "DontDestroyOnLoad" that comes with some implementations. Just have the script hold a static reference to itself that's initialized in the start method.
What about using unserialized non-monobehaviour classes? I've always thought Utility classes might be a good way to go but I hardly ever see it used by any Unity developers. Any thoughts?
I think it comes down to Unity callbacks. Some find very disturbing not having the usual callback loop like Start, Awake, Update, OnCollisionEnter, etc. When implementing manager classes, I rarely use these callbacks, so I guess, making a plain old C# singleton class is not a bad idea.
weird, do you upload 24fps ?
Ho, just saw: long exposure one. ok
anyway, nice talk Jason :)
In the last year or so, I've come to the conclusion that there's a significant difference in the inherent value of singletons between game programming contexts and regular programming contexts.
I started with Unity programming, and very often singletons seem to naturally fit in. Loading screen? Player manager? Game manager? All of these seemed almost destined to be singletons from the get-go. There would only be one instance for the game's run (Seriously, when exactly are you going to need two different uniquely functioning instances of a loading screen system?) and they need to maintain a certain state for their lifetime (I'd very much like to see a player manager that doesn't need to keep track of what inputs each player is operating).
But later on, I decided I wanted to try creating some custom porting tools to help pull out data from other proprietary formats for use in Unity. This, I feel, is much closer to the usual enterprise or other "non-game" programming contexts. As it turns out, I wound up working with libraries primarily designed to be embedded into a game, so there were a few built-in singletons I needed to work with. And I very quickly realized that, for my purposes of "just read this proprietary file and return the data inside", the management of singletons and their life cycles suddenly became substantially more cumbersome (though not impossible). I wound up creating a static HashSet of streams and had to write up some checks that track how many streams are open and initializes or decommissions the singletons once that count leaves or hits zero. Again, not ridiculous, but significantly more awkward than in the game programming context of Unity, since these tools really shouldn't need any state to determine their function; if you need to both pull and drive nails, why would you constantly switch between a mallet and crowbar when you can just use a claw hammer?
Bottom line, I think you really need to consider the context of your programming, because that will factor greatly into which patterns are or aren't useful. Just like a violinist has a much greater need for a bow than a harp player even though the violinist can still play by plucking strings, I believe game programming has a much greater need (or at the very least applicability) for singletons than enterprise programming even though statelessness still has plenty of uses for games.
Main problem I see is when they hold state that can be changed freely. Even with proper methods and hiding implementation details it can be a pain to track down why abd when something changed the global state of the singleton. It's also a static dependency which can't be changed easily or injected but you already touched that.
If you're building a singleton that just contains references to other systems and provides easy access to those systems it's less problematic (UIManager f.eg.) but global state is really evil.
If you have s script that's not intended for reuse go for the singleton because it's quick and dirty and gets the job done. When you need a layer of abstraction or need the class to be extendable or testable go for the mediator or similar event pattern. At least that's my goto.
Yeah, global state is a mess, but it's a really hard part to manage for new comers. In the past years I began to use scriptable objects instead of using singletons for state management, but it's not as easy as it sounds. Really, global state is a hard thing to get right.
@@soverain yeah you can really go wrong with singletons if you're not careful. They're can be extremely costly to refractor out, which is why I generally like to make dependencies explicit in Init methods or lookups in awake and cache as private fields.
It's not as clean as enterprise dev with the whole DI-magic but it still works good enough to make stuff testable and isolated without the overhead of a full-fledged DI-framework.
I also made a generic purpose mediator with strongly typed events which I abuse everywhere. Being able to follow events in code instead of trying to track down scriptableobject usages is a godsend for me and for testing, but I build stuff for myself not for a designer.
Again if the static dependency is not a problem for the given behavior (it's not intended for reuse) slap that singleton on it. Only use the big tools when you need them for a specific purpose.
You know what course would be AMAZING to find on Skill share (hint hint)?
A lot of people talking about how singletons are bad in the comments, but based on 5 years of daily experience with Unity/Unity communities i know that at least 80% of these people is used to have a bad performant code like Find at runtime...
I think the Singleton pattern is not used by many programmers because the pattern doesn't give any real benefit.
If you want to have one reference to something-- feel free to do so, but you shouldn't lock yourself behind that restriction.
A lot of game development is about iteration and finding what feels good.
Why limit your possibilities by using singletons?
Re: performance; I'm not familiar with performance tests using singleton architecture in game projects-- but I'll take your word that it grants some minor benefit there.
It IS used by many programmers, specially Unity programmers...
@@umapessoa6051 There's some nuance here that you're missing.
There is a difference between what is functionally a singleton -- and the design pattern of using singletons in object-oriented architecture.
And while there’s nothing wrong with having only one instance of an object (the prior), using the “Singleton Pattern” (the latter) to achieve this is never the best solution.
I won't go into the specifics here, but I'm talking more about what he mentioned regarding Enterprise applications.
And he hit the nail on the head.
Unity programming is different. You don't control a lot of the ways things are connected together on an architectural level, because it's handled by the engine. (And that's part of the benefit of using that engine, you can focus on the functions and not the architecture.)
The real question is; what's in that box that says '' DONT OPEN'?
I only use singletons, If it works it works
In Unity, to hate singletons is a kind of suicide .-.
There's a lot of different categories of "Singletons". I tried for a long time to never use them. Then I finally learned that you simply can't make a game without them. And if you do, you wasted a lot of time and confusion.
Remember, when you finish a game, most of its code is thrown away, and only experience is retained. Don't try and write it like a corporate program meant to survive re-writes and extensions for the next 2 decades.
the testing ability for singletons is extremely terrible, since you are unable to create a proper mock for it.
I love the studio's design but consider changing the lighting a little
beard reaching Dev sage levels !
I dont know if you care but some stuff in the background especially moving lights or stuff are really distracting.
Novice programmers doesn't have clear understanding about building good software architecture so it's better to teach them that singletons are bad. When they became more experienced, they will learn use cases for singletons themselves. Until that, it's better to put effort into learning solid principles or other good practices rather than trying to defy singletons.
For more experienced programmers singletons are not even a question. They can be justified in some cases, but these use cases are very limited. In general, many singletons in software is a sign of poor design decisions
It's awful you assume students are so incompetent. This demonization of a valid tool guarantees they are. Have a little hope ffs.
Singletons are fine btw. Both for novices and experienced programmers. It's not so "limited" as you pretend. You're just someone who emotionally wants to demonize them bc your "tribe" demonizes them or you were taught to.
@@nowayjosedaniel But students are limited. Human without appropriate experience is limited. It will take few years to understand how to build good program architecture.
It's not me demonizing singletons, it's hard-learned lessons from much more experienced programmers from years and years of practice
@@LSDemian Students are limited? Your argument was that the proper usage of singletons are Limited. I assume this is some ESL breakdown so I'll give you a pass here.
Do these "experienced programmers" have more experience than Jason Weimann? Unlikely.
Just stop dude. Singletons are fine. Just like all programming tools, they can be misused or abused. Nothing is safe, but you dont see people screaming about how novices should avoid C++ bc of memory leaks or how newbies shouldnt ever use While bc of infinite loops.
For those who wonder for a singleton replacement - take a look on a dependency injection frameworks. Zenject for unity is great, makes it easy to achieve same stuff as with singletons but with less drawbacks
@@LSDemian If you want people to accept a "Singleton replacement" you should start by actually making a real argument as to why they're never good. One that refutes Jason's arguments that they shouldn't be hated, since Jason makes a very strong argument to why they can be good. Otherwise, you're just saying "They're bad. Why? Because they're bad."
what is singletons?
So singletons just sound like the lazy option, sure if you got the balls and just want to make sometinge small and fast. then I can see the use.
But for everyting else not going with the right solution just sounds like the same argument for pirating a movie instead of bying it.
or peeing you pants, like it feels good and hot in the moment but later its really gonna suck. but if you gonna change you pants or are in the public pool no problem :D
Who was the first to use singleton in the history lol?
haha controversial indeed
I was full on ready to watch this 12minute video on why he doesnt hate single people XD turns out he talking about coding...
Wait almost 2 minutes to get past all the like subscribe and check out skillshare bullshit.
That was one of the worst explanations I have ever heard! Maybe try to simplify and speak to someone that doesn't know anything instead of speaking from within your own head, thoughts and experiences.
Nr of projects completely destroyed by using singletons:
99999999
Nr of projects harmed by not using them:
0
(by destroyed I mean that you can't add any feature without rewriting basically the entire game)
IDK, I wouldn't risk it, even as experienced dev.
Your background lighting is super distracting.
Singletons are controversial because people don't know how to use them. In other words, misinterpretation of singleton usage is why it's hated.
Singletons are amazing.
There is absolutely no reason to use singletons in unity.
Especially no GameObject singletons.
There is a lot of reason to use singletons, specially in Unity.
@@umapessoa6051 It's like making a campfire in your kitchen to cook food instead of using the oven right next to it.
Those things are dangerous, I've seen project which you could throw away entirely because of Singletons. And only because of Singletons, everything else was fine, commented code, variables with good names and so on.
But yea, whatever, there are more than enough other Videos out there, warning people about Singletons... it's none of my business after all.
7:50 Don't. Ever. Do. This. Or you code soon will become a horrible mess where every entity will be able to do with the player whatever they want
@@anonymous49125 in general, player code is not something that should be accessible globally
Jason Weimann - a AAA MMORPG expert game programmer with 15-20 years experience.
Dmitriy Demian - "NEVER program like Jason Weimann."
Idk who should we believe? Can you link your youtube channel or portfolio?
@@nowayjosedaniel I'll not continue this discussion if you think that your best argument is to personal attack on someone you don't know
@@LSDemian Would love any example of how "player code is not something that should be accessible globally" could lead to problems instead of sounding like something you're parroting from a programming boomer, and I'm asking this as someone that strives to avoid singletons whenever possible
@@LSDemian How is it a personal attack to point out Jason Weimann knows what he is doing? He is a well known individual and an expert game programmer.
Are you an expert game programmer? Show us your portfolio. Btw that isnt an attack to ask.