Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Understanding Singletons

Discussion in 'Scripting' started by samuelcoop59, Jul 28, 2023.

  1. samuelcoop59

    samuelcoop59

    Joined:
    Jul 15, 2023
    Posts:
    5
    I'm following a tutorial that is explaining a singleton. it starts out by using the keyword "static" for the variable public PlayerHealthController instance. Then in the awake function the "this" keyword is used. What does static mean and what is "this" referring to.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerHealthController : MonoBehaviour
    6. {
    7.     public static PlayerHealthController instance;
    8.  
    9.     public int currentHealth, maxHealth;
    10.  
    11.     private void Awake()
    12.     {
    13.         instance = this;
    14.     }
    15.  
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.         currentHealth = maxHealth;
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.        
    26.     }
    27.  
    28.     public void DealDamage()
    29.     {
    30.         // currentHealth -= 1;
    31.         currentHealth--;
    32.  
    33.         if(currentHealth <= 0)
    34.         {
    35.             gameObject.SetActive(false);
    36.         }
    37.     }
    38. }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
  3. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,317
    Honestly, you need to read introductory books about C# or help pages mentioned by spiney. This is basic level.

    "static" means variable exists as a single objects for all instances of the class (and not in every instance of the class, as it normally happens for member variables), and "this" called within class method refers to instance of the class itself.
     
    DragonCoder and Ryiah like this.
  4. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    I don't think the name here is particularly misleading. Static means "does not change", which pretty well summarizes how it works inside the computer.

    as others mentioned, for quick "what does this mean?" questions, you'll generally answer these faster by doing some 101 training with the language and asking chatgpt (just be sure to look at a few different sources each time)
     
  5. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,317
    Nope. And we just discussed "confident false information" recently.

    The idea likely predates OOP and means the variable retains values between calls meaning it is always there.

    https://en.wikipedia.org/wiki/Static_variable
     
    spiney199 likes this.
  6. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,082
    The Wikipedia article that you linked to mentioned ALGOL 60 so I went digging through old manuals and found it in one from 1965/66 (bottom-right of page 30). I thought there were times when a modern manual could be difficult to read but these old manuals are closer to white papers than actual learning material.

    http://www.bitsavers.org/pdf/sds/9xx/lang/900699C_Algol60_Ref_Nov66.pdf
     
    Last edited: Jul 28, 2023
    neginfinity likes this.
  7. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,317
    This is actually nice, as it is pretty much language spec. It is not easy to digest, but you'll know everything if your work your way through, and then it'll remain usable as a reference book.

    I also think that it was aimed at specialists, and being able to digest this sort of paper is something they should be able to do.

    As you said, nowadays this sort of structure is used for specifications and whitepapers. C++ standard is written in this way. However, the C++ standard has 1300 pages, while this one is only 42.
     
    Ryiah likes this.
  8. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    Something that tripped me up when first learning how to code was the difference between a class and an instance of a class.

    A class is the code you write, and when unity starts it then creates instances (or objects) based on that class. Some people will say the class is the blueprint and the instance is the thing that is made from the blueprint.

    That's why it's possible to have multiple copies of the same component in your game.

    So when you say "this" you are telling the instance of the class to reference itself. "Static" in the other hand means that a reference will be the same for all instances of the class.

    Using a singleton is a bit funny, because you elect a single instance to be a static variable.

    The main reason unity does this, is because it gives a globally scoped access to an instance of the class.

    It's bas code practice, but there aren't many better options in Unity.
     
    samuelcoop59 and SisusCo like this.
  9. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    can you share some examples why?

    I dont know how you could code a game without using singletons. I mean, i'm sure i could figure out a way, but I wouldnt want to. What problem do they cause in what situations?
     
  10. TheNullReference

    TheNullReference

    Joined:
    Nov 30, 2018
    Posts:
    222
    There's several reason why Singletons are considered bad coding practice. That is not the same as saying they shouldn't be use, as expedient code is sometimes useful for prototyping or small projects. Here are some issues you might run into on larger projects though:

    Global State:

    Global variables are usually considered BAD and yet that is what a Singleton is. They can be accessed anytime and anywhere in your project. This can lead to bugs where many scripts are mutating the same instance. Perhaps easy to manage if only 1-4 scripts rely on your singleton, but when 20+ scripts start referencing the singleton it can be hard to manage their access in a way that wont cause issues.

    Tight Coupling:

    In order to access the Singleton you will usually write something like "Player.Instance". Now every class in your project that references Player is tightly coupled to the Player class. Again maybe not an issue if you only have to re-write 1-5 scripts each time you want to change Player, but can become a big issue later when a change to your Player class could potentially break dozens of scripts.

    Testing:

    It's very difficult to do unit and integration tests with Singletons. Because singletons are global state they're usually going to be effected by your entire application scope, which means to test your singleton, you'll often have to load most if not your entire application.

    These are explicit issues with singletons, but there are also less direct issues with Singleton use.

    Multiplayer:

    Singletons do not allow you to have multiple instances (duh) which prevents easy implementation of multiplayer where you need multiple Player instances for example.

    Lifetime Management:

    You can't control the lifetime of your classes as easy, as Singletons exist for the entire lifecycle of the Application. It might not be appropriate to have a Player class accessible while in the Main Menu, or loading a scene.

    Misuse:

    Probably the main reason Singletons are bad, is because they're so easy. Need data access in some part of your code? slap it into a singleton. Do this enough and all your data is now Globally Scoped.

    You probably wont run into any of these issues if you're building small projects in Unity (LoadSceneMode.Single). In most cases you're only going to need 2-3 Application lifecycle singletons to handle a small game like this. As most of your data will be intra-scene. Unity doesn't provide good ways to avoid them either, so I would advise to keep using them if you're a developer for fun.

    If you ever worked on a larger project with a decently sized team (5+ developers) then singletons can quickly become the bane of your existence. At my last job we where building a fairly large multi platform application with all the bells and whistles of cloud content delivery, multiplayer, backend databases etc. It got to the point that every feature would cause at least 20+ new bugs, and even bug fixes where creating bugs. Spent 6 months refactoring the whole application, there's still a few legacy Singletons but the majority of them have been replaced.
     
    Last edited: Jul 29, 2023
  11. BIGTIMEMASTER

    BIGTIMEMASTER

    Joined:
    Jun 1, 2017
    Posts:
    5,181
    @TheNullReference

    thanks! There's a ton of follow up questions I'd like to ask, but don't want to derail too far.
     
  12. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,317
    The path is reading books, docs and practicing. Grab any programming book and do the exercises. The practice programming for several years.
     
  13. samuelcoop59

    samuelcoop59

    Joined:
    Jul 15, 2023
    Posts:
    5
    Thank you.
    Is there any particular book you would recommend?
     
  14. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,900
    Not all books, but useful:

    https://learn.microsoft.com/en-us/shows/c-fundamentals-for-absolute-beginners/

    A bunch of books. In general the Packt books are hit and miss, I can't tell you anything about the ones here listed. The O'Reilly books are basically industry standard.
    https://hackr.io/blog/csharp-books

    Free online book listing, explaining and teaching patterns in game development:
    https://gameprogrammingpatterns.com/contents.html

    If you get to the advanced level and you take it seriously, I also recommend Dr Donald Knuth's The Art of Computer programming book series. They have all kind of algorithms and exercises.
    https://www-cs-faculty.stanford.edu/~knuth/taocp.html
     
    neginfinity likes this.
  15. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,317
    The terminology is simple to the point where you only need to read explanation once, and that's it, you learned it. There's nothing to think over, nothing to ponder, no mysteries, no hidden knowledge. It is also very logical.

    Learning to program, however, takes time and practice.

    Normal behavior of a programmer or a beginner programmer is: "meet a new term" --> "read what it means" --> "move on". And not "HOW DARE THEY NAME IT THIS WAY!!!".

    No, because I learned programming long time ago, before youtube existed, and I no longer need books. If you do not know programming, you can pick any book, as you need to learn basics, and all books explain it. So either see if stackoverflow has book selection for C#, or google "C# beginner book". Lurking-Ninja's suggestions are a good start.
     
    Last edited: Jul 29, 2023
  16. Murgilod

    Murgilod

    Joined:
    Nov 12, 2013
    Posts:
    9,724
    In addition to what @Lurking-Ninja recommended, the Microsoft Learn pages in the first reply are all a part of Microsoft's extremely robust and well-written guides to C#
    https://learn.microsoft.com/en-us/dotnet/csharp/

    While not Unity specific, their tour of C# will also do a very good job at introducing you to the core concepts that make up the language
    https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/
     
    neginfinity likes this.
  17. Ne0mega

    Ne0mega

    Joined:
    Feb 18, 2018
    Posts:
    702
    Static means does not move, more than does not change, as you can change a static class.

    Its always there, and i love them.

    Its also easy to call via code without having to lug around references and assign references for everything. You can just call the class, not an instance with that class.

    Statics ate best used to hold global properties. I dont want to get too much into this, but games are constructed different ways and adventure games have different needs as opposed to strategy games, fps to rts.

    So dont let a lecture about the evils of statics dissuade you. I find them particularly helpful linking procedurally generated content with game mechanics.
     
    Unifikation likes this.
  18. DragonCoder

    DragonCoder

    Joined:
    Jul 3, 2015
    Posts:
    1,453
    What the heck happened in this thread? o_O
    OP asks a simple question and at least 20 of the 30 responses are absolutely useless discussion. No wonder people learn from ChatGPT nowadays and develop a possibly unhealthy trust in it - real people just have messed up.

    Worst is I think nobody in the discussion on whether "static" makes sense as a keyword even mentioned why it came to be:
    "static" as an adjective indeed means "not changing" but it refers to the memory location!
    No matter from where you access something marked static, it will lead to the same memory as opposed to members of regular instances.
    The implication of that is that there is only one such memory field in the software. Therefore it acts like the variable is bound to the class type itself and not to an instance.

    Absolutely nothing nonsensical about this but a helpful construct in software.
     
  19. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,955
    Clean up this thread, removed off topic and responses to off topic posts. Please stay on topic.
     
    spiney199 likes this.