Everything You Need to Know About Singletons in Unity

  Рет қаралды 88,623

Infallible Code

Infallible Code

Күн бұрын

Пікірлер: 170
@InfallibleCode
@InfallibleCode 3 жыл бұрын
NEXT VIDEO: Design Patterns in Game Development 👉 kzbin.info/www/bejne/p4SVhIOiaKx4ac0
@Juan-lj4pi
@Juan-lj4pi 4 жыл бұрын
As a person who just made his first singleton, this video makes me feel like a signed a deal with the devil.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
😂
@Woodythehobo
@Woodythehobo 4 жыл бұрын
Singleton should be renamed Blood pact.
@Juan-lj4pi
@Juan-lj4pi 4 жыл бұрын
@@Woodythehobo 😂
@Juan-lj4pi
@Juan-lj4pi 4 жыл бұрын
@The Brief man dunno if this the right answer but checking out design patterns helped me out a lot.
@subliminalcastillo2126
@subliminalcastillo2126 4 жыл бұрын
I'm glad that I heard the problems of singletons when I first started learning... It has lead me down some rabbit holes that have taken long periods of times to find alternative solutions, but that has made me learn fundamentals that I would not have learned if I would have decided to take the singleton route because it was easier.
@ChristopherYabsley
@ChristopherYabsley 4 жыл бұрын
Die hard singleton fan for many years. You can sidestep your concerns with a simple design pattern. A GameManager daddy singleton object with all your child singletons attached (on child objects for clarity sake). Make this a dont destroy on load and throw it in a starting scene that only loads once. BAM you now have access at all your singletons at all times in one guarenteed unique object. Smart use of singletons saves you writing many lines of code, which means more time to drink beer.
@simpson6700
@simpson6700 4 жыл бұрын
i wish this would've addressed the problem directly as an example: if we don't use singletons, how do we reference the player?
@christophermims6971
@christophermims6971 Жыл бұрын
public GameObject player; public PlayerScript playerScript; private void Start() { Debug.Log(player); // or GameObject gameObject = GameObject.Find("Player"); // or GameObject gameObject1 = GameObject.FindGameObjectWithTag("Player"); // or GameObject gameObject2 = this.GetComponentInChildren(); // or GameObject gameObject3 = this.GetComponentInParent(); // or GameObject gameObject4 = player.transform.parent.gameObject; // or GameObject gameObject5 = player.transform.GetChild(0).gameObject; } There a so many more easy ways to reference the player as a dependency without singletons 😃
@CheddarGoblinDev
@CheddarGoblinDev 7 ай бұрын
I use a "PlayerManager" that is the singleton. In there you can still use polymorphism for the player but have a way to access it throughout the entire codebase. In my Players "awake" method I call "PlayerManager.Singelton.RegisterPlayer(this)" and that's how the PlayerManager singleton will hold the player entity as soon as possible.
@kirukanya
@kirukanya 4 жыл бұрын
I've always been confused about Singleton patterns, and I never knew how to use them. I found this video thinking that I'd learn how to use them. but instead learnt why I *shouldn't* use them. I've just seen it being thrown around by developers on SO and Unity forums so many times that I began to think that it's a really necessary asset to an effective game. This was really insightful and I never considered how there could be so many problems in the long run that occurs as a result of misusing/overusing Singleton patterns! Thank you so much, subscribed!
@sorenmuller1974
@sorenmuller1974 4 жыл бұрын
Totally agree... Have saved several projects, which was overflowed with Singletons and hidden prereqisites.. In the beginning all is good, but as it grows, the code turns impossible to read and small changes makes it unstable.. Keep up the good work :-)
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Thanks for the comment! Yeah, Singletons are very tempting. I usually use them to cut corners but always make sure to cut them out of my project asap
@jeniferirwin
@jeniferirwin 4 жыл бұрын
I just picked up Unity three months ago and as soon as I learned about Singletons and Events, I started going buck wild with them. It seemed like they were the answers to all of my problems and I started putting them everywhere... and now I'm watching videos like this one trying to figure out how to properly break my project up into more manageable parts. My project has reached an unpleasant critical mass that's almost impossible to work with! This video is making me now think much more carefully about whether the singletons I have actually need to be singletons in my planned 'grand refactoring.' Thank you for these videos, they're extremely helpful!
@DrewofDonuts
@DrewofDonuts 2 жыл бұрын
You pulled me off the singleton ledge as I was nearly about to implement it for my Player. Thank you
@erz3030
@erz3030 4 жыл бұрын
Great presentation Charles :) It's clear you spend much time considering your preparation, presentation, and editing of these videos. You make very relatable and easy to follow examples. IMO, your down to earth nature is your best asset making this sort of content, and sets you apart from others in your own way. Keep up the great work!
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Thank you, I really appreciate the feedback!
@aldigangster123
@aldigangster123 4 жыл бұрын
I know of the "bad reputation" of Singletons for a couple of months now, but you are the first who gives concrete "evidence" why so. Thanks!
@jaykinbacon2379
@jaykinbacon2379 2 жыл бұрын
First, In your awake() method, the first singleton can be destroyed unless you also compare that the object isn't identical to itself. Secondly, Unity API is not thread-safe, but Singleton must be thread-safe. You must include a lock to your singleton's instance to prevent multi-thread issues. Thirdly, even with the practice in place, you'd ultimately run into another error where simply "ending" the game/project will cause an unusual exception. Singleton can be re-created upon application shutting down. You ultimately need to find a way to prevent the instance from creating itself. The trick to do so is to check the gameobject if it has the DontDestroyOnLoad flag checked. If true, you can safely exit the property by returning null. Hope this helps! I really enjoy watching your channel!
@joaniepepin4968
@joaniepepin4968 4 жыл бұрын
I've seen way too many projects where they were used everywhere to pass data around and that was terrible, but completely avoiding them is a big radical : They are still the best solution for common needs such as an Audio Manager. If all you want to do is play an audio clip, you may get around just fine with a static class, but if you want anything more complex, the limitations of a static class quickly gets in your way and cleanly passing that single instance of your Audio Manager to every objects that can make a noise in a large project would qickly lead to a ton of spaghetti code.
@jaykinbacon2379
@jaykinbacon2379 2 жыл бұрын
Usually in this case, a singleton might be ideal to get your game going and get things functional until you iron out the mechanics you want to establish. Then slowly convert the singleton objects into normal object when the code are in place and set. This process usually take some time, but worth in the end by decoupling all of your code into basic game logic pattern and behavior. This effectively save you and your teams a tremendous amount of work to push out milestone updates for every fix/patches in your game.
@estranhokonsta
@estranhokonsta Жыл бұрын
@@jaykinbacon2379 Basically every code in the planet uses some form of singleton in one way or another. They just hide them in many labels or structures or other programming paradigms besides OOP. In the extreme one only has to remember what 'main' and 'Program' is (or whatever other label you use) to begin to see it. "Converting a singleton" in itself is a good process since we are taking out concerns of the singleton that don't really belong to it and will no doubt bring headaches in the not so much long run. But no matter how much one " slowly convert the singleton objects into normal object", there will always be one in the end. The singleton concept is essentially a relative one and a necessary one. Denying singletons just because people use them badly is another way of being a poor programmer.
@jaykinbacon2379
@jaykinbacon2379 Жыл бұрын
@@estranhokonsta Please treat them like class. Each planet would have their own unique property. How are you going to identify a particular planet? use a singleton to provide you "scene" information, e.g. How many planets do I have? Or technically `public int PlanetCount() { return _itemDictionary.Where( i => i is T ).Count(); } `
@newarteest
@newarteest 2 жыл бұрын
aha, thanks for elucidating that idea of exposing your dependencies with a list of private fields at the top. I use a service locator pattern to get references to shared manager objects, and while I knew in my gut this is an improvement over turning those managers into singletons, until you said that I had trouble verbalizing WHY that is an improvement.
@PXLJUC
@PXLJUC 4 жыл бұрын
FindObjectOfType as you said returns the first object of that type that it finds but a caveat you forgot is that it's the first ACTIVE object of the type it finds. So if you deactivate an object which has the singleton on it, for some reason, FindObjectOfType will no longer find it and therefore return null letting you create another. FindObjectsOfTypeAll includes deactivated objects but is far slower since it does not stop at first found.
@lossycoffee9282
@lossycoffee9282 4 жыл бұрын
Wow this probably saved me a lot of trouble. I was trying to find out how to do a Selection script. I thought "Only one thing is ever selected and whatever the player is controlling will need to know a couple details about what is selected, I'll make it a singleton since there should only ever be one instance so everything can grab it. But this really convinced me out of it. Maybe I'll decide that I want to pass a more specific thing to the player based on what is being Selected, such as an enemy or a treasure chest. But more importantly the talk about thinking about "weather or not your WHOLE GAME really needs access to this data" made me realize I really only need this to be accessed by the player controller-- nothing else in the game really cares what the player has selected. Thanks so much! I can tell it might have been easy now, but I really could've tangled my code (again, and had to rebuild my passion project from scratch for a 5th time lol! It's ok, I learn lots every time so rebuilding only ever takes a day or two.)
@TommyAck102
@TommyAck102 4 жыл бұрын
Kinda like the Hitchhiker's Guide to the Galaxy on Vogsphere: " I asked the guide for the best way to use Singletons, it said Don't.....I'm assuming you have a better plan?"
@CheddarGoblinDev
@CheddarGoblinDev 7 ай бұрын
I use singletons solely for "Manager" classes/components that - well manage - other entities like Enemies or Items etc. It's just a quick way for me to manage or get information to those collections of entities everywhere. Those entities by itself however are subscribed to certain events I broadcast from my "*Systems" class (that also are Singletons). This kind of architecture design works like a charm. I am working on a MMORPG project and this approach really works well so far. However I am also a professional web engineer and only use Dependency Injection on those applications. Never using singletons for web apps and server applications. I like it that way. So I am using both "paradigms" in two different genres which shows that both ways have their right to exist.
@noodle-eater
@noodle-eater 4 жыл бұрын
Another role model to be followed, awesome videos dude.
@pirateskeleton7828
@pirateskeleton7828 2 жыл бұрын
I have singleton for my player. Specifically, the singleton figures out what object I'm currently controlling, which lets other classes know where to generate terrain and move the camera, but that part of the system works more like an event system, with the guys who need to know the player location subscribed to a notification function. I call it the Player Manager.
@unitydeveloperkgk9836
@unitydeveloperkgk9836 2 жыл бұрын
These videos are gold. Best coding videos I've seen in 8 years. You will eventually get a good sponsorship.
@Tarodev
@Tarodev 2 жыл бұрын
"Fenagling". What an interesting word.
@kuinks
@kuinks 4 жыл бұрын
This has always been a heated debate even outside of gaming. Dependency Injection and Service Locator are alternative patterns to the Singleton pattern, but they unfortunately have some important bad aspects that are critical for games: They make things harder to debug, reason about, promotes runtime errors rather than compile time errors when dependencies are missing, and also have some performance costs. This is a big deal for game development. This is why if you do some research you'll likely find a lot of game developers using Singletons. I think this video should explore a little bit more on the alternatives and have a better reasoning about why Singleton is probably a good option too.
@Shibis
@Shibis Жыл бұрын
Indeed
@teslavoltagames3208
@teslavoltagames3208 4 жыл бұрын
Logger, audio manager, math library, and game manager are all examples of good use cases for singletons which fit all of your criteria. I wouldn't use them for anything, but if you have a single use case that will be accessed seemingly at random all over the code, it is better than using Dependency Injectors and flinging around 20 parameters into every class.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Be careful not to confuse static classes with singletons. Something like a math library doesn’t have a state, so it shouldn’t be a singleton but instead a collection of static methods.
@teslavoltagames3208
@teslavoltagames3208 4 жыл бұрын
@@InfallibleCode I know what static classes are. Sure a math library can be static classes with methods, but the other examples are fine. Trying to use Dependency Injection into every single class destroys traceability, adds a huge amount of boiler plate code that is a pain to maintain, and causes massive parameterization of virtually every class. It is not a one size fits all solution no matter what Bob Martin says.
@stylezhouse
@stylezhouse 4 жыл бұрын
I like the video, but I love your setup. That ambient lighting looks amazing!
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Thank you!
@Amheklerior
@Amheklerior 4 жыл бұрын
Good job with this video Charles. I can only immagine how tough it has been to make such a clear explanation about this topic in such a short amount of time. Well done ;D
@ravanin
@ravanin 4 жыл бұрын
Please do a singleton alternatives vid!!
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Check out my video “How To Access Variables From Another Script In Unity” for an alternative approach to using. Singletons kzbin.info/www/bejne/Y5zHZ2urgNlnoM0
@erdiizgi5189
@erdiizgi5189 4 жыл бұрын
Here you go, medium.com/@erdiizgi/avoiding-singletons-yeah-the-evil-ones-cc1538de021e
@RobertBojor
@RobertBojor 4 жыл бұрын
Thanks for this. I've moved away from singletons (since they were causing more headaches than solving things) and ended up using the "GameMaster" in all the scenes and referencing it in the scripts I needed.
@3rdClassFilms
@3rdClassFilms 4 жыл бұрын
But how do you keep track of data between scenes then?
@LeviAckerman-xt7dx
@LeviAckerman-xt7dx 3 жыл бұрын
Lol I'm pretty sure game master is also a singleton
@spxctreofficial
@spxctreofficial 3 жыл бұрын
I instantiate my player from a prefab at the start of runtime. Not only does this allow the GameManager/GameController to have full control over the player (since the GameManager would be the class that instantiates the player in the first place), but also allow the GameManager to have control over which version it should instantiate as the player GO. This means that, within the GameManager, you have control over the player that you instantiate, as well as what prefab you want to instantiate as the player. Probably a weird way to do things, but it might just work with some tinkering!
@eyefisher
@eyefisher 4 жыл бұрын
Extra points for referencing the Ballmer Peak! (Remember Windows ME?)
@sergiisechka1993
@sergiisechka1993 2 жыл бұрын
Finally someone told me what is singletone, huh thank you!
@Galakyllz
@Galakyllz Жыл бұрын
Thanks for the video. I already agree with you for all of the reasons you mentioned and I hope that this helps other developers write better code.
@lescoe
@lescoe 4 жыл бұрын
You're a really good presenter. You definitely deserve more subscribers.
@DiscoStu492
@DiscoStu492 4 жыл бұрын
Great video. Very informative. Was wondering about singleton usage in game dev code, specifically in unity. Love the channel as a whole too. 👍
@TheNamesJT
@TheNamesJT 4 жыл бұрын
I would like a video on how to do dependencies without using a singleton since using find object of type and getcomponent is performance costly
@Streamweaver
@Streamweaver 4 жыл бұрын
All comments here are good advice, it does get confusing, it should be noted though that there ARE some tools to help troubleshoot this. in VS or Rider it tells you how many references there are to something so there are some tools to deal with this if you keep it in check.
@quanghong3922
@quanghong3922 4 жыл бұрын
More design pattern please
@betterlifeexe4378
@betterlifeexe4378 2 жыл бұрын
generic instance management with a default singleton-like behaviour with multi-instance handling is my way to go. And, done with enough generics, you can mostly copy and paste it from project to project. in the end, you have a dynamically generated instance referencing to your generic tools (probably namespace) that has a default constructor instance (probably the first member of a list) with the ability to have a collection using the same pointer. When in the editor, I recommend it load a second instance so that you can debug concurrency.
@betterlifeexe4378
@betterlifeexe4378 2 жыл бұрын
the dynamic reference also can have a null coalescing operator to avoid reassignment by default, or it has optional parameters for crud
@DaDylanMachine
@DaDylanMachine Жыл бұрын
I'm still kinda new to Unity development so I didnt fully understand your explanation on Singletons, but with how you describe using them... maybe thats a good thing lol.
@Luvseatshawty
@Luvseatshawty 2 жыл бұрын
Thanks for the perspective on this video. I'm not sure but I think my overuse of singletons in the form of "manager" classes has thrown my game out of whack because I'm getting false null exceptions in my game manager. I'll be studying this video for a while 😂😂
@darryljf7215
@darryljf7215 4 жыл бұрын
I agree, I'm cautious about their use though I do use them sparingly. For me the big problem with singletons is that a humble value type (struct) can change global state. This is enough for them to be banned :)
@lando6583
@lando6583 4 жыл бұрын
this guy changin up the unity tutorial game!
@SHOOTINGDNA
@SHOOTINGDNA 4 жыл бұрын
Based on this I'd only use singletons for prototypes/ or really tiny projects with well defined scope.. like flappy bird, or astroids kinda games.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Yeah pretty much. I use them to cut corners during development, but never with the intention of actually using them.
@MaZyYTube
@MaZyYTube 4 жыл бұрын
I use a technique where I use singleton with scriptable object assets. This means it will never on scene as gameobjects. Best part.. you can add prefabs or other things. But also have bads. You can create multiple assets, if is not reference somewhere you need to resources folder or its not included in the standalone version and the last, its loaded when the game starts forever.
@BeenZone
@BeenZone 2 жыл бұрын
I am completely confused, so might come back too this later lol
@Faygris
@Faygris 4 жыл бұрын
Finally someone managed to explain this without just dropping empty phrases like "it breaks the OOP concept". Now even I understand why I shouldn't use singletons anymore
@umapessoa6051
@umapessoa6051 3 жыл бұрын
You should use, the question is HOW you use.
@Hezekiel112
@Hezekiel112 5 ай бұрын
thanks for covering this topic 👍
@tombruckner2556
@tombruckner2556 3 жыл бұрын
The pure reason why I am using Singletons: Unity tends to kill injected references at random, especially if (nested) Prefabs are involved. This is completely uncontrollable and can kill the whole game, if it is unnoticed before release. This annoyed me so much that Singletons turned out to be a life-saver. However, I don't reference the instances directly, but rather at the beginning of each file only, via "private Player player => Player.Instance". This makes the dependency transparent and easy to change.
@PereViader
@PereViader 4 жыл бұрын
Here you go, take my positive feedback. This one made me happy. I am a little harsher, and would not allow for singletons. Ever. Even when they can be used, you can go by just fine without them and this prevents any bad habits and possible future requirement changes that make a singleton not a singleton any more.
@bugwar5545
@bugwar5545 3 жыл бұрын
Thanks for the explanation.
@InfallibleCode
@InfallibleCode 3 жыл бұрын
You're welcome!
@dmtuan
@dmtuan 4 жыл бұрын
Had to like the video just for the intro! :D
@Donevigor
@Donevigor 4 жыл бұрын
Where did you get that cup? Looks awesome
@InfallibleCode
@InfallibleCode 4 жыл бұрын
My wife got it for me in the Germany section of Epcot. Love this thing!
@shattered_prism
@shattered_prism 4 жыл бұрын
@@InfallibleCode i think it's called a "Stein" (instead of cup)
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Yes, that is correct
@tracy449
@tracy449 4 жыл бұрын
Thanks for the video. However you didn't hit the most important underlying principle regarding why not to use a singleton in the way you mentioned: Never store the a single variable in more than one place.
@unfa00
@unfa00 2 жыл бұрын
I'd love to hear how this translates to the Godot engine. Singletons the are easily managed in the project settings and unless you implement the pattern from scratch - you don't have to worry about managing them manually. The are strictly global.
@skelhain
@skelhain 4 жыл бұрын
Is it ok to use singletons as notification center for global subscription and invokation and as a blackboard (shared knowledge) for ai?
@doismilho
@doismilho 2 жыл бұрын
I'm honestly not convinced. Still seems useful AF to me and the negative side-effects you describe have just never been an issue to me. Also just to notice, I do keep the reference on each script that will acess the singleton, usually, especially if very frequently. I make a private field of the singleton type and on Start, attribute it to the singleton instance. Just to save me the trouble of finding it some other way like "findobjectbytag", I hate tags. Also referencing in inspector is something I avoid. Mostly because I tend to instantiate things via code and I dont trust the scene to keep it's inspector references intact. People will edit that same scene, or sometimes by editing the script the references get lost and so on.
@ozonexo3
@ozonexo3 4 жыл бұрын
Singletons should not be used everywhere and definitely not in case like Player that can be instantiated everywhere or there can be many of them (for coop or multiplayer). But what about case like that: Instantiating particle effects in runtime is expensive so we created FXmanager that instantiate all of them that are needed on level load (like a pooling system). Then when we need to play FX we just call static FXmanager.PlayFx(enum type, transform parent) and to do that FXmanager need to be a singleton - to have access to all instanced particles, and to be easily accessible from any scripts. We never expose any variables or its instance, only controls it with static voids so all logic is inside manager and we only send him something like events. Also all singletons are stored in "Core" scene and only there, we never instantiate them. We first load whole level and then additive load Core. Is there a better way of doing that? How you design things like AudioManagers or other PoolingSystems? I will like to find a better solution for next projects. Removing singleton and when using only events on instanced monobehavior we dont know if there are many of them. If there is more than one we will have multiple particles played instead of one. Changing it to static or scriptableObject will "disconnect" it from its instanced particles and can cause issues when we unload Core scene or we want to release particles from memory by removing them from DontDestroyOnLoad. That causes it to behave somewhat similar to singleton so it will need to manage all of its instances, but maybe that still a better solution. I dont like your videos about singletons and accessing variables, because after watching them i still dont know how to do it better. I would like to see more in depth examples whats wrong and how it should be done.
@hauntedcrowdev
@hauntedcrowdev 28 күн бұрын
What other options are there for data persistence aside from using singletons? For example, player properties like "life points" that need to be saved and consistent when changing from scene to scene.
@PurpleDaemon_
@PurpleDaemon_ 4 жыл бұрын
I was looking for information on the proper use of singleton an hour ago ... P.S.I am one of those who have never used singletones and would like to understand when they should be used.
@Hoptronics
@Hoptronics 6 ай бұрын
I might be late to the party . But when I clicked this video on Singletons and he mentioned Coffee.. I said, "I think you mean beer." And so he did . Lol .
@ShehzadAkhtar2010
@ShehzadAkhtar2010 4 жыл бұрын
Amazing explanation
@LittleTreeX
@LittleTreeX Жыл бұрын
"Everything you need to know about Singletons in Unity EXCEPT alternatives....".
@aurelienlerochbermuda6600
@aurelienlerochbermuda6600 4 жыл бұрын
Nice video, but where is the other Charle ?
@InfallibleCode
@InfallibleCode 4 жыл бұрын
He’s still trying to wrap his head around the State Pattern lol but he’ll be back soon.
@N1ghtR1der666
@N1ghtR1der666 4 жыл бұрын
I mean if you have setup that singleton so that the public function was change health then there would be no problem with your example, ChangeHealth could do whatever you want and you could change it how you like without effecting the objects referencing it, the problem seems to come from when you design refence public variables directly or you have a public function do something too specific then its problematic if you need to change what it does. the singleton could have a function added called ApplyArmor and that could be called from ChangeHealth so it changes the health based on an armor value or some multiplier etc.
@lukereynor8737
@lukereynor8737 4 жыл бұрын
Fantastic Video Thanks!
@Studio1XN
@Studio1XN 4 жыл бұрын
oh singletons... you cover my path with a swarm I wish I never had found these lessons. I was happy writing code warm in the land of C# I will never find the end. Its sad my friend.
@magnusm4
@magnusm4 10 ай бұрын
I'm implementing a singleton now cause the Unity Netcode Network Manager spawns players at the same spot with no way of choosing where. There used to be a component for this according to legacy documentation, but for some reason it's vanished. So I need a way for all connecting players to be spawned where I want.
@grimoirescarlet1481
@grimoirescarlet1481 3 жыл бұрын
To avoid hiding the dependency can't you just store a reference to the singleton at the start and then use that reference to access the singleton? That way you keep the code clean but avoid hiding your dependence and if change need to be done you just have to change said reference rather than the whole code.
@ZenitDS
@ZenitDS 3 жыл бұрын
What font are you using? It looks nice and I would like to use it in my editor.
@InfallibleCode
@InfallibleCode 3 жыл бұрын
It's call Victor Mono and I highly recommend it
@ZenitDS
@ZenitDS 3 жыл бұрын
@@InfallibleCode Thanks.
@hesamom1781
@hesamom1781 4 жыл бұрын
Nulls and singletons are two things that ruined more lives than saved.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Definitely! I need to do a video on nulls and the null object pattern next!
@hesamom1781
@hesamom1781 4 жыл бұрын
@@InfallibleCode Great! I'm looking forward to it!
@richardguilliams7278
@richardguilliams7278 2 жыл бұрын
(I do forsee some potential issues like using my loopdebugger in more than two loops at once would throw off its counter property) so my singleton is just a dubugger class that formats and logs whatever type of data is fed to it. things like that shouldnt cause confliction issues right?
@lwyz8a
@lwyz8a 2 жыл бұрын
The only time i need to use a true Singleton, is when making a Server Handler/Manager, to read and write data to a server, it needs to be globally accesible by any script and it can only be one instance, since it needs to live though all scenes and every time a scene loads it usually needs to read data from the server, but I'm curious if there's a workaround when dealing with this problem. For any other time, I don't use singletons, only some scripts with public statics instances to be globally accesible and nothing more.
@sicksharkx92
@sicksharkx92 4 жыл бұрын
@infallibleCode What about EventsManager? do you think is better to decouple two classes with simple events or use a event manager singleton?
@StigDesign
@StigDesign 4 жыл бұрын
Interesting nice explaned :) i youst got started on making a GameManager that handl`s all my Track`s and Car`s bool`s hehe :)
@TorchWind
@TorchWind 3 жыл бұрын
Could I make "microsingletons" to go around this problem? For example: If I want to make the music not stop between scenes, instead of having my entire AudioManager have "don'tdestroyonload" I could make it instantiate a "GameMusic" GameObject with it that plays the music if there isn't one in the scene already. Is this approach valid? Am I overthinking this? Am I missing something?
@yensid46
@yensid46 2 жыл бұрын
So did I miss something? if I am building something that is not a game but has multiple scenes loading and I need a reliable way of creating a property that I can get and set during use of the application, what other method would you suggest to make sure that only one instance of the class exists so that I am pulling the information from the property when needed or setting it when i need to. I really enjoyed the way you presented this information but that annoying little loop of music in the background made me want to drink a case of beer. And I don't drink alcohol.
@3333218
@3333218 4 жыл бұрын
What about using Interfaces and Service Locators instead? And what about Dependency Injection frameworks that allow you to declare some object as Singleton elsewhere?
@jaykinbacon2379
@jaykinbacon2379 2 жыл бұрын
For non-game singleton patterns, please look into Jon Skeet's singleton examples. Jon's blog provides full details and information as to which singleton examples may be suited for your project needs.
@3333218
@3333218 2 жыл бұрын
@@jaykinbacon2379 Will do! Thanks!
@fgcbird
@fgcbird 2 жыл бұрын
I really only use them in the audio manager case
@tchq
@tchq 3 жыл бұрын
Sad, that you've stopped making videos.
@InfallibleCode
@InfallibleCode 3 жыл бұрын
Just for a little while. I'm getting ready to start producing more videos that should come out soon!
@tchq
@tchq 3 жыл бұрын
​@@InfallibleCode Good to hear. Don't forget to invite Barles! :-))
@arunachalpradesh399
@arunachalpradesh399 2 жыл бұрын
hi inflalible is singleton efficent for cpu or heavy?? please reply
@BlakeKane
@BlakeKane 4 жыл бұрын
One more reason to not to use singletons: You destroy second singleton class while being created at awake and if you forget to use keyword return; right after destroy, all your awake code will be executed including event registration which will cause evets` listeners to execute twice or more depending on how many times you ve tried to create singleton class. Singletons are a tool in toolbox. Right. But they should be handled extremely carefully like static variables and should be used only but only needed.
@BRINK2011THEGAME
@BRINK2011THEGAME 4 жыл бұрын
What’s the difference on using a static class and a singleton ?
@SathishKumar-jz3wh
@SathishKumar-jz3wh 4 жыл бұрын
what extension you are using in vs to show the "usage" above every function?
@rafaelcordoba13
@rafaelcordoba13 4 жыл бұрын
Avoid singletons and static classes. Learn some TDD and how to write cohesive and modular code. Use Zenject for Dependency Injection. Use FluentAssertions and FakeItEasy for quality of life when writing unit tests.
@PeterMilko
@PeterMilko 4 жыл бұрын
I cant code if I drink alcohol, would not recommend. Im a game dev come look
@georunstar
@georunstar 3 жыл бұрын
You get a like for that fine pilsner
@louisgjohnson
@louisgjohnson 4 жыл бұрын
Kinda weird that you don't host the example code on github or anything.
@workflowinmind
@workflowinmind 4 жыл бұрын
The title should be "the dark side of singleton" you don't really go over when to actually use them.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
You should never use them ;)
@workflowinmind
@workflowinmind 4 жыл бұрын
​@@InfallibleCode ​ Oh that explains why! I'm building an app in Unity (like Mixer did), and I have not found better ways than singleton for some aspects (selectable objects & gizmos for instance) but I'd love to be wrong, I saw another comment about this I'd love to see a video about when you think you need them and what you should use instead. PS: nice channel, I love your duo with Charles
@GreenHorseYT
@GreenHorseYT 4 жыл бұрын
Come back to my place and I'll invert your dependencies if you know what I mean.
@InfallibleCode
@InfallibleCode 4 жыл бұрын
xD
@nocultist7050
@nocultist7050 4 жыл бұрын
I'm working on PersistentObjectManager and my mind for some reason focused on making it a singleton. I'm still not sure it's the best solution and I have troubles wrapping my mind around different singleton implementations. My case fulfills all criteria: It needs to exists only once, so all data is saved in one instance and there is no randomly undata. Must be accessible from every and all PersistentObjectBehaviour scripts. Yeah saving and loading so exactly the mentioned case.
@JordonRenn93
@JordonRenn93 Жыл бұрын
Maybe my project isn't big enough but just can't seem to understand the downside in my project
@jigar.bhanushali
@jigar.bhanushali 3 жыл бұрын
i agree to each and every bad points of singleton but but but i am one from the die heart fans of singleton instead i'll say addicted to singleton singleton deserve addiction badge because every daily user of singleton are aware of its harm but we still use it anyway similarly like any other addiction alcohol , cigarette , or drug
@alvin4100
@alvin4100 3 жыл бұрын
Thanks for this didnt realize how potentially a pain in the ass singletons can be.
@MatrixQ
@MatrixQ 4 жыл бұрын
So maybe someone can help me out here. I'm currently in the process of learning Unity by creating a point and click adventure. I've been rewriting the code numerous times, when I figured out something new. Lately, I've found singletons and the event system to make an excellent composition in my eyes. I have a singleton event manager that all the interactable items in the game can subscribe to when their scene gets loaded, and I can just do it without having them go about getting the component first. Now sure, I could have all the items find the event manager first and subscribe that way, but it feels like that would be step that's not really needed with the singleton pattern. And since I'm only using the one singleton, that's sitting in a persistent scene that additively loads all the other scenes, I don't really see the harm in using a singleton here. Or would the GetComponent method of addressing the event manager actually be the better one here, if only to see the reference in the rest of the classes? I don't know, it feels like since everything is built around the event manager anyway, that would be a moot point. If not, I'll gladly be told differently. Or maybe there's even a completely different way of doing this?
@N1ghtR1der666
@N1ghtR1der666 4 жыл бұрын
I would love to see an answer to this
@MatrixQ
@MatrixQ 4 жыл бұрын
@@N1ghtR1der666 My own answer at this point: Using a singleton isn't a problem, if you know what you're doing. So for example having a GameManager singleton that coordinates the rest of the game is perfectly fine. Having too many of them (to the point of turning everything into a singleton) is going to give you bad headaches.
@N1ghtR1der666
@N1ghtR1der666 4 жыл бұрын
@@MatrixQ thats kind of my general thought too, I feel its blasphemy to say around here though lol
@tozzo6481
@tozzo6481 4 жыл бұрын
That nice face in the thumbnail tho
@InfallibleCode
@InfallibleCode 4 жыл бұрын
Thanks xD
@Holagrimola
@Holagrimola 3 жыл бұрын
this is rather "everything wrong with singletons in unity" than everything I need to know. I need to know exactly how they work, which this video doesn't deliver :/
@romantroshkin3142
@romantroshkin3142 6 ай бұрын
The implementation of the singleton suggested in this video is suboptimal. The author seems to hate singletons in favor of DI.
@jugger6228
@jugger6228 3 жыл бұрын
well let's rewrite my singleton scripts D:
@appolos5116
@appolos5116 4 жыл бұрын
nice vid
@Othello379
@Othello379 3 жыл бұрын
Somthing about the introduction of this video and the comment section makes me feel there is something bad with singeltons 😬
@smallflyDE
@smallflyDE 2 жыл бұрын
Came here to hear how singletons work. Now leaving and don't want use singletons anymore. ^^
How to Handle Errors in Unity
5:24
Infallible Code
Рет қаралды 24 М.
Why I Don't Like Singletons
29:05
The Cherno
Рет қаралды 89 М.
amazing#devil #lilith #funny #shorts
00:15
Devil Lilith
Рет қаралды 18 МЛН
Каха и лужа  #непосредственнокаха
00:15
小丑揭穿坏人的阴谋 #小丑 #天使 #shorts
00:35
好人小丑
Рет қаралды 40 МЛН
Why I don't hate Singletons?
11:30
Jason Weimann (GameDev)
Рет қаралды 26 М.
Singleton Design Pattern in C# - Do it THAT way
13:15
tutorialsEU - C#
Рет қаралды 28 М.
Better Coding in Unity With Just a Few Lines of Code
15:27
Firemind
Рет қаралды 314 М.
Truth about Singletons in Unity | New GameDevs WATCH!
16:49
Jason Weimann (GameDev)
Рет қаралды 17 М.
How to Code a Simple State Machine (Unity Tutorial)
19:22
Infallible Code
Рет қаралды 163 М.
SOLID Principles in Unity
14:58
Infallible Code
Рет қаралды 153 М.
Command Pattern in Unity
11:21
Infallible Code
Рет қаралды 75 М.
How Thinking in Systems Can Improve Your Code
10:16
Infallible Code
Рет қаралды 32 М.
Here's How You Should Be Thinking About Data
10:56
Infallible Code
Рет қаралды 35 М.
Singletons in Unity (done right)
7:26
Game Dev Beginner
Рет қаралды 15 М.