Learn to Program with C# - SINGLETON DESIGN - Intermediate Unity Tutorial

  Рет қаралды 52,728

GameDevHQ

GameDevHQ

9 жыл бұрын

In this video we take a look at the Singleton design pattern in C#. For more information and in-depth knowledge of C# and Unity, check out The Unity C# Survival Guide, available at GameDevHQ.com
MAKE YOUR OWN GAMES THIS YEAR:
bit.ly/2Vg56Kt
► Discord
/ discord
► Subscribe
bit.ly/2EqewxV
#unity3d
#indiedev
#gamedev
FREE UNITY C# TUTORIALS:
Want to learn to make games?
Unity C# Tutorial for Beginners - • Learn to Program with ...
Unity C# Tutorial Intermediate - • Learn to Program with ...
Unity C# Tutorial Advanced Coding - • Learn to Program - LIS...
---
Have a tutorial suggestion? Send it to us on GameDevHQ.com.
Social Media Profiles
Facebook: / gamedevhq
Twitter: / gamedevhq
Website: gamedevhq.com unity 2018 tutorial

Пікірлер: 107
@ZacVrono
@ZacVrono 9 жыл бұрын
Mind BLOWN! I never thought of doing this. super useful man. These are the best game programming tutorials for unity and just C# in general around. I feel like I learn more in 10minutes of your tutorials than most 1-2 hour lectures.
@unkindled_dreg
@unkindled_dreg 7 жыл бұрын
So happy I found your channel, I watch these when I travel to work and whenever I get time too. It's coding in plain English, which makes it so easy to understand. I never understood properties and singleton until I watched this tutorial. Thanks, Jon!
@Patricebrouh
@Patricebrouh 5 жыл бұрын
Great video! Now I really understand this concept of Singleton thanks to this video.
@tr3vorx
@tr3vorx 3 жыл бұрын
great video series. great complement to unity's courses
@whatevsimbulletproof
@whatevsimbulletproof 5 жыл бұрын
Amazing playlist! Subscribing for more unity programming stuff!
@priyeshjain4554
@priyeshjain4554 7 жыл бұрын
Just noticed that you replied to every comment so just wanted to say Hi and of course thanks for your amazing videos :)
@Christopher4700
@Christopher4700 8 жыл бұрын
that was freaking loud! 6:40
@Christopher4700
@Christopher4700 8 жыл бұрын
6:38 :)
@blzahz7633
@blzahz7633 6 жыл бұрын
*HEART* *ATTACK*
@moonroll1985
@moonroll1985 4 жыл бұрын
WTF man O_O So scary me!
@oguzhan3630
@oguzhan3630 4 жыл бұрын
F
@Twinji
@Twinji 7 жыл бұрын
Hi, great video! I have a question: is lazy instantiation the only benefit to using the singleton pattern for managers over, for example, static classes? Or are there any other significant benefits?
@sufianahmad7337
@sufianahmad7337 3 жыл бұрын
Thank You
@nitras.design
@nitras.design 8 жыл бұрын
Thanks for your tutorial, however a few questions. is it good to refer to a camera and ui items in this class? for example send the score to the class that deals with the text in game. Right now I have an individual class that does some text animation. However the camera finds the player from within the game manager class. dealing with deaths and respawns is dealt within the gamemanager. also the difficulty. Not sure if I fully understand this concept. Thanks!
@TwistdRabbit
@TwistdRabbit 2 жыл бұрын
Great tutorial, one question though, can this be done using private fields instead of public? im trying to get a score system across multiple scenes of a platformer for a college assessment but i have to keep all class-wide variables private.
@PolylabStudio
@PolylabStudio 3 жыл бұрын
NO LONG INTRO JUST STRAIGHT FORWARD VERY EASY TO UNDERSTAND.
@oleksandrshvets
@oleksandrshvets 2 жыл бұрын
Sitting up at night doing your lesson at 6:41 I almost jumped when there was a sudden loud sound. Please don't do that again ))
@V1TOCHIN
@V1TOCHIN 4 жыл бұрын
do you typically do this with the Player class too? Since there is only 1 player class ?
@bryanwulzen450
@bryanwulzen450 7 жыл бұрын
Excellent video, thank you! I have one question about this that has me a little bit confused. I don't quite get how a game in unity is composed of multiple different scenes, and how the game manager interacts with those scenes. Do you need to have the game manager script exist as an object in every single scene? Or is there a different way to handle this? Thanks!
@josh_swanson
@josh_swanson 4 жыл бұрын
static class doesnt get destroyed between scenes
@leatherandpoemscharmyman5774
@leatherandpoemscharmyman5774 4 жыл бұрын
private and only one instance right? the first step ? what's is the relationship with abstract class, I learning basic and intermediatly codes years ago but I stopped it to learn , and now this year I strting again ,not by 0, I started with class and arrays. thx!! you are very didactic with strong fundamentals!
@gmostechnologicalvlo
@gmostechnologicalvlo 7 жыл бұрын
I'll be honest, I'm a really lazy guy, that does not have a lot of time, but thanks to this video, I managed to understand this pattern. Thank you for that.
@gmostechnologicalvlo
@gmostechnologicalvlo 7 жыл бұрын
***** why did you stop btw?
@gmostechnologicalvlo
@gmostechnologicalvlo 7 жыл бұрын
***** glad to hear, that things are working out for you.
@funkyjedi
@funkyjedi 7 жыл бұрын
Jonathan Weinberger Your tutorials should be on Udemy and alike, you have more than enough great content so the rest is discoverability - being where people are already interested in this type of work is the key.
@soonfamous
@soonfamous 6 жыл бұрын
Hey John, great example of the Singleton pattern. My only concern is that in order to make use of it in a script e.x GameManager. Any serialized fields, lets say a gameobject prefab will have a null value if if the GameManager Instance is created through the approach you suggested of a new gameobject and attaching the script to it. I ended up using a UnitSpawn Manager that was instantiated in the scene in order to update the values I needed but I wonder if there is a better work around. Thank you in advance and also congrats on your Udemy courses, I am really enjoying it!
@GameDevHQ
@GameDevHQ 6 жыл бұрын
In this case, you wouldn't use the Lazy Instantiation of a Singleton. You would already have it living and breathing in the scene and then be able to add whatever objects to it you want. when you check for if it's null, you wouldn't instantiate it, you would throw an error that would stop the program
@soonfamous
@soonfamous 6 жыл бұрын
Makes a lot of sense. I am looking at your observer pattern material now, I want to compare it with the Mediator pattern and see what use cases should they fit. Thank you again!
@ngoquoctruong302
@ngoquoctruong302 9 жыл бұрын
Singleton is powerful pattern that must learn as soon as i started to develop game with any engine. So, why dont you make a separate topic to talk about design pattern and which one common use when you code Unity ? I know that way maybe not help someone can make a game quickly. But i think that can optimize system when we take large project. Anyway, i appreciate your tutorial .It encourage newbie eager to learn Unity.
@timmydube4379
@timmydube4379 2 жыл бұрын
How are these different then just using static variables on a manager script?
@catherineclaudet5515
@catherineclaudet5515 7 жыл бұрын
Hi John, thanks so much for the tutorials!! I have a lot of manager classes I'd like to make into singletons but some of them require different property values depending on the scene I'm in. I still only want one of them at any given time, but since I want different properties for different scenes, am I unable to make a singleton? If not, what's the best practice for setting up a singleton which needs different property values for different scenes? Hope I'm being clear. Thanks a lot!!!
@catherineclaudet5515
@catherineclaudet5515 7 жыл бұрын
I see! Thanks so much for getting back to me!
@AlexjW3
@AlexjW3 2 жыл бұрын
@@catherineclaudet5515 The reply was deleted, how did you approach this?
@andrewpeterson5016
@andrewpeterson5016 9 жыл бұрын
Awesome video as always! Just wondering, is there a specific reason you decided to capitalize the auto property variables in the GameManager class instead of keeping them lowercase? (public int Score{get; set;} AND public bool IsDead{get; set;})
@KillIt43
@KillIt43 9 жыл бұрын
***** I Dont Under Stand Properties and managers Why Would I use these for I tried to make this Health Thing Work Why get something if you cant change it for example: this is the first script: using UnityEngine; using System.Collections; public class Stuff : MonoBehaviour { private static int _currentHealth = 100; public static int CurrentHealth { get { return _currentHealth; } set { _currentHealth = value; } } // Use this for initialization void Start () { Debug.Log (_currentHealth); } } ============================================================ This Is Going to Be The Second Script... ============================================================ using UnityEngine; using System.Collections; public class Suff1 : MonoBehaviour { // Use this for initialization void Start () { Debug.Log(Stuff.CurrentHealth = 10); } } ============================================================ It Prints Out 10 Thats good But When I Put Something in the first script it did not work why can you Help me.. i really need help on this one; maybe a skype call.... and also why is this useful for can you give me example why will i use this properties and manger???????????? Please Relay :/
@KillIt43
@KillIt43 9 жыл бұрын
Kill It43 I Know that its Changing but why would i want to change something when i can just change it in the script like public int health = 10 if(input.getkeydown) //health = 10 or something like that... can you please help me why will this be us-full in anyway.... same goes for the gameObject.GetComponent help me with this i under stand this but why will i use this ;;;;;get;;;; = your getting the component set; == your setting that variable a value; please........
@KillIt43
@KillIt43 9 жыл бұрын
***** I Know But Theres 3 Ways you can get 1. Static 2. Propertes 3. GetComponet
@steunwell
@steunwell 8 жыл бұрын
+Kill It43 in programming you want the most of your stuff to be read only to prevent potential errors by modifying it in others scripts. So basically you hide your variable BUT you provide a way to reference that variable / edit it outside the script.
@tonnytay9372
@tonnytay9372 9 жыл бұрын
Understand the purpose of it, but actually using it is confusing. Can a singleton be a ClassManager for instance a class manager for knight/archer/mage etc. with properties? I remember looking around the web about singletons and saw a MusicManager. So bit confuse on this managing thing. Saw your other videos about Namespaces and Interfaces and such, they are somehow similar to Singleton Manager I think. Can all of these work together with the Singleton?
@springfield-videos
@springfield-videos 5 жыл бұрын
You need to lock the thread if the instance is not null in case of multi-threading otherwise it will not be thread safe.
@danielguevara9357
@danielguevara9357 6 жыл бұрын
PLEASE ADD A COMMENT IN THE VIDEO THAT YOU MUST ADD THIS TO THE AWAKE FUNCTION = DontDestroyOnLoad(this); because if you dont add that code you will instance over all the scenes and the values of the variables will be reset I almost get crazy but I figure it out, thanks for the video I wrote all the code you preset on it and helps me a lot!!
@aliozer861
@aliozer861 2 жыл бұрын
Great video but this code.. "GameManager.Instance.Score" isn't it a little long and complicated to just get the score variable ?
@alexisbedard9211
@alexisbedard9211 9 жыл бұрын
Hey There Jonathan, I really like your serie but I have a question. I initialized the propertie score in void Start() to 10, but when I came to Debug.Log score in my Player script, it showed 0. Then I messed around to try to find why, and wrote this(still in my player script): void Start () { Debug.Log (GameManager.Instance.score); } void Update () { if (Input.GetKeyDown (KeyCode.Space)) { GameManager.Instance.score += 1; Debug.Log (GameManager.Instance.score); } } At starts, it says 0. When I hit the space key once, it says 11, like if it doesn't know I initialized score before. Do you know why? Thanks a lot!
@alexisbedard9211
@alexisbedard9211 9 жыл бұрын
puu.sh/hmh7M/02532b5bc8.png puu.sh/hmh8j/31f829b33f.png There you go :)
@ThanhTran-jr3iw
@ThanhTran-jr3iw 4 жыл бұрын
Cần you show me when we have instance == null?
@stephenmandelbaum2027
@stephenmandelbaum2027 4 жыл бұрын
Not gonna lie, this broke my brain a little.
@Kathayne636
@Kathayne636 3 жыл бұрын
You and me both.
@furroy
@furroy 7 жыл бұрын
when i make code changes and it hot swaps in a new compiled class, this seems to break the singleton. any work arounds for this?
@furroy
@furroy 7 жыл бұрын
i made a singleton for my player like you showed. in my ladder class i have a method private void OnTriggerEnter2D(Collider2D collision) { PlatformerCharacter2D.Instance.EnterLadder(gameObject); } if i edit my PlatformerCharacter2D class and make some changes, all the ladders start getting null pointer errors calling Instance property. it seems it doesn't call Awake() again after the hot swap so the singleton is never reassigned
@KeenanWoodall
@KeenanWoodall 9 жыл бұрын
How would I go about setting up component/object references in a singleton so that the singleton doesn't have to find all of the objects on Awake/Start. If I had a script that controlled the lighting and I wanted my singleton to reference it, how would I do that? Right now I have properties on each object references in the singleton. Each object's get property checks itself to see if it is null, if so I'm using GameObject.FindObjectOfType to set up the reference. Until the reference is needed it isn't finding the necessary object. However, when I try and access the variables I get a null reference error. Here's my example code: pastebin.com/bmhBcezN
@ptelephant
@ptelephant 9 жыл бұрын
One thing that keeps tripping me up in these videos is the "this" keyword. It seems pretty versatile, and I'm not entirely sure when the best instances are to use it. Could you define what it means and does a little more? I've done internet searches to look it up, but it only made it worse and the one definition I have seems a little specific to the case in which it's being used.
@ptelephant
@ptelephant 9 жыл бұрын
Cynthia Breheny I think I figured it out :)
@ptelephant
@ptelephant 9 жыл бұрын
That's what I figured! Thanks so much for getting back to me though! It was good to have confirmation.
@xoxovladimirxoxo
@xoxovladimirxoxo 6 жыл бұрын
i still don't understand the use of it.
@josh_swanson
@josh_swanson 4 жыл бұрын
the purpose is to have a class that only exists once and can't be instantiated that contains public variables that every other class can access without having to create or search for it.
@hasanshafy_
@hasanshafy_ 4 жыл бұрын
@@josh_swanson Could you give me a scenario? It'd really help.
@gogoldgoal
@gogoldgoal 4 жыл бұрын
Hasan Shafy say you have a bank account and a addCoin function, and every other objects in the game want to use that function. If you singleton it, it saves you time keep referencing the bank account and get component in every scripts every time. All you need to do is t Just BankAccount.addCoin , like Time.deltaTime
@jayocaine2946
@jayocaine2946 4 жыл бұрын
@@gogoldgoal bad example, you could reference that script literally any other way that doesn't involve making a singleton if all you want to do is use a single function.
@wholebitmedia
@wholebitmedia 5 жыл бұрын
This code returns an error of missing assembly reference when assigning its component to go. Also returning instance can cause a stack overflow....
@GameDevHQ
@GameDevHQ 5 жыл бұрын
Hey Terry! hastebin.com your code and I can take a look or post it on gamedevhq.com
@wholebitmedia
@wholebitmedia 5 жыл бұрын
I only meant to say that if I had invoked a method from my other script using the exact code in this tutorial such as : GameManager.Instance.Move(vertical,horizontal,character,cam); I would receive that message("missing assembly reference") , Also when my game slowed to a crawl, it pointed to the return instance line as a stack overflow. Just letting you know what happened on my end. :)
@KurisuFariasAguila
@KurisuFariasAguila 4 жыл бұрын
@@wholebitmedia I assume you did something like public static GameManager Instance { get { ... return Instance; //
@artjom5617
@artjom5617 4 жыл бұрын
so i am also a beginner and for everyone still not understanding it: you can access variables from every other script in singletons.. thats how i understand it. so if you need to slow down a every enemy, you just call the singleton variable and set the number from 1(100%) to 0.5(50%). if i am wrong, correct me please :)
@aarondelgado3421
@aarondelgado3421 4 жыл бұрын
I would not recommend singletons to be used.
@artjom5617
@artjom5617 4 жыл бұрын
@@aarondelgado3421 i never recommended it, i just explained it :)
@HYBRIDER-YT
@HYBRIDER-YT 4 жыл бұрын
What is the difference between doing this and just making the class static?
@mustafageo
@mustafageo 4 жыл бұрын
I can see one difference: You can have public global properties in the instance which you can't have in the static class.
@erikm9768
@erikm9768 6 жыл бұрын
Doesnt seem to work, my GameManager's attributes are all reset after sceneload anyway :/ particularly score which i added just like you did.
@erikm9768
@erikm9768 6 жыл бұрын
yeah i added DontDestroyOnLoad and then it worked, but then i dont really see the purpose of the singleton.btw is that in your video?? it should be. thanks!
@darkman237
@darkman237 8 жыл бұрын
Would this work well for dealing with databases?
@darkman237
@darkman237 8 жыл бұрын
I wanted a manager that had all the database set up and functions in one place and accessible from anywhere. This is for an RPG desktop game and an android app. Two very different programs.
@darkman237
@darkman237 8 жыл бұрын
Thanks! New question- I seem to be having trouble accessing one script from another. Not sure if it's a monodevelop glitch or something else. I created a reference to one and tried to access the other. While it came up and seemed to work, the function I called didn't execute. Any thoughts?
@darkman237
@darkman237 8 жыл бұрын
I don't have hastebin- other thoughts?
@darkman237
@darkman237 8 жыл бұрын
So, how does it work? I can't see that it saves anything anywhere. How would you be able to see the code??
@darkman237
@darkman237 8 жыл бұрын
hastebin.com/dulapemiqu.avrasm
@ankitraj3180
@ankitraj3180 4 жыл бұрын
only singleton pattern is enough for unity developer(fresher) or do i need to learn more design pattern sir??
@josephsaidogabriel7740
@josephsaidogabriel7740 7 жыл бұрын
What is "this", what does "this" refer to? This class this object?
@josephsaidogabriel7740
@josephsaidogabriel7740 7 жыл бұрын
Thanks! I like your tutorials.
@pokoro97
@pokoro97 5 жыл бұрын
I wouldn't use a singleton to record a player's dead/alive status. Maybe the game's running/not running status. The player object should have it's own health and isDead property. Also, singletons might be ok for small games, but I think you'll run into problems if you try to do anything with them at a production level.
@GameDevHQ
@GameDevHQ 5 жыл бұрын
Thanks for the comment. Large enterprise applications are built with Singletons. I've built enterprise apps for Coke, AT&T, the Casino Industries, and several video games. Singletons are great :)
@SeberyGames
@SeberyGames 5 жыл бұрын
im disagree, if you have just one player, you will need just one health and isDead property, so you will need a singleton
@geldonrashidi4572
@geldonrashidi4572 8 жыл бұрын
CAn't Understand what Singeltons Are :/ !!!
@geldonrashidi4572
@geldonrashidi4572 8 жыл бұрын
+Jonathan Weinberger Good suggestion :-)
@nikigoodfellow7511
@nikigoodfellow7511 6 жыл бұрын
Take note of the meaning of the word "Singleton" = "a single object". So an INSTANCE of a single object (the script)
@lalabee92
@lalabee92 6 жыл бұрын
Chappeh55 what is the use of having one instance.is it harmful to have multiple instances?
@spellweavergeneziso
@spellweavergeneziso 6 жыл бұрын
No, the point is, many times in games, there are some objects, that you know they will only have one instance. For example, if there is a finish point in a game, you know there is only one. One object -> one instance, this is the case when you use Singleton. Also, as mentioned in the video, the "Player" -> you playing the game, are also a Singleton. So basically sayin, you are singleton in every single game you play. Like in your life, there is only one YOU, that you control, that you live with, there are no others.
@reed9269
@reed9269 6 жыл бұрын
yes one finish,but why to create singleton, why not regular. so what if its once or not. if its one finish, and i say ontriggerenter() { Finish Race; } thats it. i dont see how singleton applies. the thing i try to say is : its once in game, so what.
@wasiimo
@wasiimo 9 жыл бұрын
I am so confused go.AddComponent(); WTH i still have no idea what this is and why its useful. Class or object? just way to confusing.
@wasiimo
@wasiimo 9 жыл бұрын
***** i just dont get it is the gameManager just a script? and why are you checking if the gameManager is there? i watched the whole vid its just confusing what you are trying to do.
@wasiimo
@wasiimo 9 жыл бұрын
***** Can you just use if statements to check? why would you need to hold state information? and why would there be more than one game manager and i did watch your previous videos i just can't grasp the concept i want to understand it unless you show me the why state machines are better and dont tell me to many if statements well cant you organize those if statements into methods?
@JustinS06
@JustinS06 4 жыл бұрын
Ready to get a heart attack?? 6:41
@KillIt43
@KillIt43 9 жыл бұрын
Why Change Private variables its something you never want to change
@steunwell
@steunwell 8 жыл бұрын
Private is used to make sure variable is not accessible outside of the class without getters/setters. A variable that won't be changed is a constant variable.
@haykav
@haykav 5 жыл бұрын
I think you are confusing private variables with constants
@Ragnark1
@Ragnark1 5 жыл бұрын
This works: using System; using UnityEngine; public sealed class GameManager : MonoBehaviour { private static bool isInitialized = false; private static readonly Lazy _instance = new Lazy(() => new GameManager()); public static GameManager Instance { get { if (_instance != null && !isInitialized) { GameObject go = new GameObject("GameManager"); go.AddComponent(); // isInitialized could go here // isInitialized = true; } return _instance.Value; } } public int Score { get; set; } public bool IsDead { get; set; } private void Awake() { isInitialized = true; } }
@thattrollagen
@thattrollagen 3 жыл бұрын
If you just need the code he stops talking and starts typing at: 2:26
@monkeyrobotsinc.9875
@monkeyrobotsinc.9875 3 жыл бұрын
GOOD programmers dont make good artists or TEACHERS. i dont like this video. you didnt explain ANYTHING TO ME
@GameDevHQ
@GameDevHQ 3 жыл бұрын
sounds like a personal problem.
Learn to Program with C# - ENUMS - Advanced Unity Tutorial
12:26
Smart Sigma Kid #funny #sigma #comedy
00:19
CRAZY GREAPA
Рет қаралды 21 МЛН
Everything You Need to Know About Singletons in Unity
8:38
Infallible Code
Рет қаралды 86 М.
The 6 Design Patterns game devs need?
24:20
Jason Weimann
Рет қаралды 361 М.
Singletons in Unity (done right)
7:26
Game Dev Beginner
Рет қаралды 10 М.
Learn to Program with C# - INTERFACES - Advanced Unity Tutorial
13:07
Rust's Most Important Containers 📦 10 Useful Patterns
17:11
Code to the Moon
Рет қаралды 114 М.
Singleton Design Pattern Tutorial
18:40
Derek Banas
Рет қаралды 461 М.