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

Am I abusing static classes if all I want is a quick reference?

Discussion in 'Scripting' started by Shack_Man, Dec 22, 2018.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    365
    After getting used to using Singletons when it is important to only have one instance of a class at a time, I kinda developed the habit of using static classes for quick reference while forgoing the whole Singleton thing.

    Code (CSharp):
    1.     private static LevelManager instance;
    2.     public static LevelManager Instance
    3.     {
    4.         get
    5.         {
    6.             return instance;
    7.         }
    8.     }
    9.  
    10.     private void Awake()
    11.     {
    12.         if (instance == null)
    13.             instance = this;
    14.     }

    Sometimes I have classes that just use LevelManager in one or two lines of code, so instead making a variable and using something like FindObjectOfType<LevelManager>(), I just use LevelManager.Instance.

    Is this bad practice? Particularly when it comes to performance? I can understand that I should limit the amount of classes that are allowed to access and modify my LevelManager, in this case every class, but my project is small and I think I can handle it. I don't like using serialized Fields either because that's where errors happen: Sometimes I have to reassign everything manually after changing the scene.

    Thanks
     
  2. eneroth3

    eneroth3

    Joined:
    Oct 22, 2018
    Posts:
    63
    Is this on a monobehavior attached to a GameObject? I'm not experienced enough about Unity to judge the pattern as a whole, but if it is used I would consider it bad practice not to check if there already is an instance and warn if a second one is created (assuming there can only be one). Defensive coding helps your future self.