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

Question What should I be aware of if I use a static class?

Discussion in 'Editor & General Support' started by IIBearWithII, Apr 26, 2023.

  1. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    I'm still new to both C# and Unity. I know static classes can't inherit things like MonoBehaviour. What exactly will that prevent me from doing? Because I noticed I can still say "using UnityEngine"...

    Also, I'm just using a static class to store and share simple data like strings and integers with various objects in the scene, so does anyone have any general advice or warnings for a beginner?

    Here's what I know so far from google:
    • A static class cannot be inherited from another class.
    • A static class cannot be a base class for another static or non-static class.
    • Static classes do not support virtual methods.
    • A static class cannot implement an interface.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,707
    Using a static class is fine as long as you NEVER contemplate having more than one of these things.

    A static class is not an instance so it could never be "dragged into" anything in the Unity editor.

    I use static classes all the time for anything that I will only ever have one of, or that mirrors an existing static engine property.

    The biggest thing is that the CIS types will howl endlessly about how it is bad design. These people can be safely ignored up to the point where your game's needs exceed what can be done with a static

    Another warning about static is that YOU become fully in charge of it. This means if you have a
    public static int Score;
    the it is ON YOU to reset it to zero before each game, etc.
     
  3. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    Ok, thanks! Just to be clear, if I make a platformer game with a static class that keeps track of player stats, each time the game is loaded I will load the save data. So that should be fine I think. But I think you're warning me that if somehow the player dies, and I go back to another scene, I have to manually reset the data in the static class. Is that right?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,707
    Correct. That's the key: even if you make a brand-new player, load a brand-new scene, if that player or scene reaches over to that static score, it will still be the same value.

    Here's an ultra-simple static GameManager solution example:

    https://gist.github.com/kurtdekker/50faa0d78cd978375b2fe465d55b282b
     
    Unifikation likes this.
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,721
    A static class prevents you from doing the most important thing typically associated with classes (and object-oriented programming in general) - creating objects based on that class. Instead you are limited to static fields and static methods. It's more or less a way of writing non-object oriented code in what is otherwise an object-oriented language.
     
    IIBearWithII and Kurt-Dekker like this.
  6. Unifikation

    Unifikation

    Joined:
    Jan 4, 2023
    Posts:
    1,043
    One other thing to be aware of... Static classes tend to be in "better memory", so operate a little faster, in all sorts of ways.
     
    IIBearWithII likes this.
  7. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    Ok, got my code working with static classes. The book I'm studying had me create a script that put made static properties of some classes that weren't originally static, which, as a beginner, I hadn't seen before an it confused me. Then those references were put into a list to iterate over and call the startup functions for those classes. Maybe that's why he did it that way? From what I've been reading, you can't put static classes in a list. But apparently from the book's code you can make static properties of regular classes and put those in a list?


    Why can't you put static classes directly in lists?

    Also, if I do this, (where PlayerStats is a class):

    Code (CSharp):
    1. public class SomeClass : MonoBehaviour{
    2.     public static PlayerStats PlayerStats1;
    3.     public static PlayerStats PlayerStats2;}
    does that create two separate instances of PlayerStats, where I can store different data?

    Meanwhile, if I just make PlayerStats itself static, I'll only ever be able to have one version of the data. Is that correct?
     
  8. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,721
    It doesn't create any instances of anything. It defines two static PlayerStats references. Since PlayerStats is a class, this just means you have two reference variables. These variables can refer to instances of the PlayerStats class if you assign them with the = operator, but are otherwise just null.

    Because, as mentioned before, static classes don't actually let you create any objects from the class. Lists contain objects. No objects means nothing to put in a list.
     
    IIBearWithII likes this.
  9. Unifikation

    Unifikation

    Joined:
    Jan 4, 2023
    Posts:
    1,043
    Here's a video I think is probably compulsory viewing for any new Unity user:



    And Kurt is the absolute master of these, and many other aspects of thinking through how to best use Unity and stay sane!
     
    IIBearWithII likes this.
  10. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    Yeah, they fields were assigned component reference using the Editor.

    Thanks for explaining the lists, I get it now!
     
  11. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    I'll take a look, thanks!
     
  12. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    I watched it. I'm curious what people's opinion's on this is. On one extreme, you can avoid static things entirely, and then, on the other extreme you have the Singleton approach it seems. For a beginner, I don't want to close any doors, especially ones that might keep my code from getting too cluttered, but the Singleton approach does still have problems you have to watch out for, so I'm kind of hesitant to use it. At least right now. I'm thinking somewhere inbetween the two approaches might be good for me right now. Using a few static classes for some commonly used data, and then for the rest dragging and dropping references and using GetComponent.
     
  13. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,707
    Doors are meant to be closed.

    If you realize you need something behind that door you open it back up.

    This is called broadly refactoring.

    Two of the most useful tools to have in your head when refactoring are:

    - a firm grasp of what you are attempting to achieve

    - a firm grasp of where your project stands now and how it lets you down

    From there you can reason about alternate methods and make the necessary changes.

    It is SOFT-ware after all, not HARD-ware.
     
    Unifikation likes this.
  14. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87

    Not sure I can agree with you on doors being meant to be closed. I'd prefer to think of doors as having the ability to give access to a space when desired, and deny access when not. But this is getting kind of philosophical, lol.

    All I meant, anyways, was that I wanted to stay open-minded so that I could "make the necessary changes" down the road if needed, but was looking for advice on how a beginner should navigate the two extremes.
     
  15. Unifikation

    Unifikation

    Joined:
    Jan 4, 2023
    Posts:
    1,043
    There's so much signal/noise from the world of OOP programmers about their supposed negatives of Singletons and Static Classes (and functions) that you must, for your own sanity, find ways to be agnostic about programming religions... of which OOP and Functional Programming advocates are almost equally bad.

    Games are different from other types of coding endeavours. Performance always matters. Many things are interacting per frame, and worlds need to be built up and torn down, real time monitoring of input and events is needed, with the ability to instantly communicate between objects and systems, systems and objects, systems and systems, and object and objects. Contexts need to be changed out (level switching) and all manner of other concerns with regards the creation and utilisation of temporary effects exist that aren't in normal app programming.

    As a result, Manager systems and Systems of management and optimal paths for creativity and exploration need to coexist.

    So do it the easiest way, even if that's a little brittle, and simply rewrite those manager systems and mangers whenever is needed.

    Kurt can explain all of this far better than me, and better than just about anyone ever has, as he thinks deeply about the ease with which game making should be and the expense of conventions and mantras from other industries and frameworks.

    Don't be misled by the fact that you've been graced by his presence, and don't take his advice lightly. He is far and away the most considerate and concerned user of Unity and his commentary and insights are truly invaluable.
     
    Shushustorm and PraetorBlue like this.
  16. CiroContns

    CiroContns

    Unity Legend

    Joined:
    Jan 28, 2008
    Posts:
    74
    There's one tiny little thing that people keep forgetting when it comes to static classes in Unity. If you embrace static in a "fire and forget" way, you lose the ability to use Enter Play Mode Settings

    Screenshot 2023-04-28 alle 00.19.10.png

    Docs: https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html

    By unchecking these two options (located in Project Settings > Editor), entering Play Mode will be considerably, and I mean CONSIDERABLY - faster.

    However, by choosing not to reload Domain you need to watch your statics. Whatever is declared as static, will have its values from the last play session. So you need to basically cleanup when you exit play mode (or in OnDestroy, OnDisable, etc.) - or, initialise things to defaults when you enter it. You can't rely on things being in a "clean" state.
     
    IIBearWithII, Ryiah and icauroboros like this.
  17. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    I've found Kurt's advice helpful in the past and am continuing to find his advice helpful. It's His setup I am currently using for my static managers. Did I disagree on some minor philosophical thing, yes. But no offence was intended, and I would definitely apologize if any offence was taken.
     
    CiroContns likes this.