# Static class or Singleton?

**URL:** <https://discussions.unity.com/t/static-class-or-singleton/457184>\
**Category:** Scripting\
**Tags:** Scripting\
**Created:** [October 3, 2011, 3:11pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184 "2011-10-03T15:11:20Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![orionburcham](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/orionburcham/32/413998_2.png) [@orionburcham](https://discussions.unity.com/u/orionburcham)\
**Post date:** [October 3, 2011, 3:11pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/1 "2011-10-03T15:11:20Z")

</div>

I’m having some trouble understanding when to use static classes vs singletons in my code (or if singletons are acceptable at all -from what I’ve read, seems like some people think they’re irresponsible).

Let’s say I’ve got a gameState field in my game manager script that I’m looking to switch out with a new gameState at various points in my game.

1. The way I was thinking of implementing this was by creating some public static classes for each gameState in my class library, then setting my GameManager’s gameState to = one of the static gameStates.

2. Or, I figure, I could use a singleton pattern for each gameState (still in my class library), but I’m not sure what the advantage would be… unless…unless I need an instance in order for this to work, since I can’t have the GameManager gameState = a type? And a singleton does exactly that- creates a single instance of a static type in your class library? Actually that seems to make total sense, but any clarification or advice would be very helpful.

Thanks for any tips!  
Orion

---

<div class="post-metadata">

**Author:** ![andorov](https://avatars.discourse-cdn.com/v4/letter/a/9d8465/32.png) [@andorov](https://discussions.unity.com/u/andorov)\
**Post date:** [October 3, 2011, 3:24pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/2 "2011-10-03T15:24:46Z")

</div>

A Singleton just creates an instance of your class and usually prevents new instances from being created, like so…

```auto
public class SomeClass 
{
	public static Instance 
	{ 
		get 
		{ 
			if (_Instance == null) 
				_Instance = new SomeClass(); 
			return _Instance; 
		} 
	}
	
	private static _Instance;

	private SomeClass() { }
}

```

A couple of the reasons why I find singletons to be better is because they CAN be inherited. They can also be destroyed and recreated in some cases (like, for example, resetting your game/level). I follow the singleton pattern for the vast majority of the things because it is the most flexible.

---

<div class="post-metadata">

**Author:** ![HarvesteR](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/harvester/32/352582_2.png) [@HarvesteR](https://discussions.unity.com/u/HarvesteR)\
**Post date:** [October 3, 2011, 3:25pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/3 "2011-10-03T15:25:50Z")

</div>

Well, I think of it like this:

If a class has no real need to use the Unity API, make it static.  
By using the Unity API, I mean really use it. Like heavy dependence on the attached objects or something… If you just need to print to console, or instantiate/destroy objects, you can just use the API’s own static methods from your static class.

Now, if you really need to integrate your class with a GameObject, but need to expose global data, then it’s a singleton.

The way I do my singletons is this:

```auto
public class MySingleton
{

    private static MySingleton fetch; // keep the static reference private
    
    public bool myBool = false;

    // and expose static members through properties
    // this way, you have a lot more control over what is actually being sent out.
    public static bool MyBool { get { return fetch ? fetch.myBool : false; } }

    void Awake()
    {
        fetch = this;
    }
}

```

Cheers

---

<div class="post-metadata">

**Author:** ![anon\_67940662](https://avatars.discourse-cdn.com/v4/letter/a/57b2e6/32.png) [@anon\_67940662](https://discussions.unity.com/u/anon_67940662)\
**Post date:** [October 3, 2011, 3:34pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/4 "2011-10-03T15:34:17Z")

</div>

Some people consider Singletons bad because they tend to create a lot of coupling and dependencies on external sources (i.e. if your login rountines reference your player Singleton then you can’t test logging in without a Player anymore, without having to hack through your code). They do definitly have uses, but can also be abused and used too much to create spaghetti code.

That being said I personally over use them and am trying to cut back. They are easy to setup but on bigger projects, without a lot of early planning and design can get you into trouble later on and make your code base a mess.

---

<div class="post-metadata">

**Author:** ![KelsoMRK](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/kelsomrk/32/205687_2.png) [@KelsoMRK](https://discussions.unity.com/u/KelsoMRK)\
**Post date:** [October 3, 2011, 3:34pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/5 "2011-10-03T15:34:37Z")

</div>

> [@andorov](#):
>
> A couple of the reasons why I find singletons to be better is because they CAN be inherited.

A singleton that can be extended isn’t a “true singleton” since you’ve opened up the potential for multiple objects of the same type to exist.

I personal prefer the singleton pattern over an all-static class. Just feels safer to me for whatever reason.

---

<div class="post-metadata">

**Author:** ![orionburcham](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/orionburcham/32/413998_2.png) [@orionburcham](https://discussions.unity.com/u/orionburcham)\
**Post date:** [October 3, 2011, 4:10pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/6 "2011-10-03T16:10:59Z")

</div>

Thanks, everyone- that helps a lot.

For anyone confused about this in the future, I also found this link very helpful:

> **[Differences: Static Class vs. Singleton Patterns - DZone](https://dzone.com/articles/c-singleton-pattern-vs-static-)**
>
> Discover the differences between the singleton design pattern and the static keyword on C# classes for storing common data.

---

<div class="post-metadata">

**Author:** ![justinlloyd](https://avatars.discourse-cdn.com/v4/letter/j/76d3ee/32.png) [@justinlloyd](https://discussions.unity.com/u/justinlloyd)\
**Post date:** [October 3, 2011, 6:54pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/7 "2011-10-03T18:54:18Z")

</div>

This is how I do my MonoBehaviour “singletons” in Unity.

Please note that my “singleton” code does not t try and save the programmer from themselves, if they wish to be contrary and access the “singleton” instance from a totally static class before Unity has had a chance to instantiate anything then that is considered user error and the problem exists between the keyboard and chair, not with the code.

The “singleton” will also politely destroy itself and the object it is attached to if the programmer attempts to attach the behaviour to more than just a single game object. Again, the error is on the part of the user, not the part of the code. You could modify the code to catch this latter case if you are working in a team with more than one programmer.

```auto
public class GameController : MonoBehaviour
    private static int m_referenceCount = 0;

    private static GameController m_instance;

    public static GameController Instance
    {
        get
        {
            return m_instance;
        }
    }

    void Awake()
    {
        m_referenceCount++;
        if (m_referenceCount > 1)
        {
            DestroyImmediate(this.gameObject);
            return;
        }

        m_instance = this;
        // Use this line if you need the object to persist across scenes
        DontDestroyOnLoad(this.gameObject);
    }

    void OnDestroy()
    {
        m_referenceCount--;
        if (m_referenceCount == 0)
        {
            m_instance = null;
        }

    }

```

---

<div class="post-metadata">

**Author:** ![cregox](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cregox/32/372683_2.png) [@cregox](https://discussions.unity.com/u/cregox)\
**Post date:** [September 18, 2013, 8:05pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/8 "2013-09-18T20:05:12Z")

</div>

I haven’t even read this, but want to add a shameless link to a related discussion: [http://forum.unity3d.com/threads/197169-Singleton-vs-Static](http://forum.unity3d.com/threads/197169-Singleton-vs-Static)

Also, I want to promote the **[singleton](http://wiki.unity3d.com/index.php/Singleton)** usage. Go singlies!

---

<div class="post-metadata">

**Author:** ![Errorsatz](https://avatars.discourse-cdn.com/v4/letter/e/77aa72/32.png) [@Errorsatz](https://discussions.unity.com/u/Errorsatz)\
**Post date:** [September 18, 2013, 10:27pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/9 "2013-09-18T22:27:30Z")

</div>

I often use the “pseudo-singleton” approach - have a class that acts like a singleton to other scripts, but is manually placed on an object in the scene, allowing its parameters to be set on a per-level basis.

One handy thing about having an actual GameObject involved is that it will receive an OnDestroy message and then you can simply clear the instance reference to clean it up. In many games, it’s important not to leave static references to GameObjects/textures/etc laying around when a level ends, or you’ll prevent cleanup of those resources.

However, that’s somewhat irrelevant to the interface of the class - even a class that internally has a singleton instance can use static functions as its public interface.

---

<div class="post-metadata">

**Author:** ![BFGames](https://avatars.discourse-cdn.com/v4/letter/b/34f0e0/32.png) [@BFGames](https://discussions.unity.com/u/BFGames)\
**Post date:** [September 18, 2013, 10:36pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/10 "2013-09-18T22:36:34Z")

</div>

When i code in Unity use Singletons for my Controller classes like GameController, GUIController, NetworkController and so on, classes that handle an overall part of the game. I use static classes to hold methods for stuff like math libs and such, which might be used in all classes including my singletons.

---

<div class="post-metadata">

**Author:** ![cregox](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cregox/32/372683_2.png) [@cregox](https://discussions.unity.com/u/cregox)\
**Post date:** [September 18, 2013, 10:39pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/11 "2013-09-18T22:39:18Z")

</div>

So you both should definitely check out the wiki singleton I’ve already linked. Here again: [http://wiki.unity3d.com/index.php/Singleton](http://wiki.unity3d.com/index.php/Singleton)

---

<div class="post-metadata">

**Author:** ![Errorsatz](https://avatars.discourse-cdn.com/v4/letter/e/77aa72/32.png) [@Errorsatz](https://discussions.unity.com/u/Errorsatz)\
**Post date:** [September 18, 2013, 10:56pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/12 "2013-09-18T22:56:20Z")

</div>

I’ve seen that one. However, that’s for “pure” singletons. The type of “pseudo-singletons” I’m talking about are part of the scene, and have parameters that are set in the scene. Creating a blank instance wouldn’t be desirable.

For example:

```auto
class GameSettings : Monobehaviour
{
  // Parameters, set via the inspector
  [SerializeField]
  private int difficulty;

  // Public interface
  public static int Difficulty 
  {
    get { return Current.difficulty; }
  }

  // Current instance management
  private static GameSettings _current;
  private static GameSettings Current
  {
    get
    {
      if(_current == null)
        Debug.LogError("Attempting to access GameSettings before it's been created.");
      return _current;
    }
  }

  void Awake ()
  {
    if(_current != null)
      Debug.LogError("More than one copy of GameSettings exists.");
    _current = this;
  }

  void OnDestroy ()
  {
    _current = null;
  }
}

```

Non-template version shown for brevity. That’s using the “static interface” design - you could alternately make Current public and make Difficulty non-static.

---

<div class="post-metadata">

**Author:** ![fire7side](https://avatars.discourse-cdn.com/v4/letter/f/a88e57/32.png) [@fire7side](https://discussions.unity.com/u/fire7side)\
**Post date:** [September 18, 2013, 11:54pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/13 "2013-09-18T23:54:39Z")

</div>

I don’t use either one very much, but I think a singleton is used for something there is only one, but it has a state. A static class is more used as a group of helper functions with static data. A game manager might be a singleton, a helper class, a static.  
It’s kind of a mute point for me since my games are never going to get that large. I would rather worry about using object pools or something.

---

<div class="post-metadata">

**Author:** ![angrypenguin](https://avatars.discourse-cdn.com/v4/letter/a/aca169/32.png) [@angrypenguin](https://discussions.unity.com/u/angrypenguin)\
**Post date:** [September 19, 2013, 12:47am UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/14 "2013-09-19T00:47:21Z")

</div>

I used to use them a lot, but have moved towards loosely coupled event systems and am so far loving them.

Basically I have a bunch of static delegates which represent events, with parameters which represent any information that a receiver may care about arising from the event. Any object which cares about any event can subscribe to it by adding a method to the relevant delegate. Any object which does the thing an event represents calls the delegate and passes in relevant information. Neither the receiver nor the performer of the event has to be aware of one another.

This does open a few risks, but I’ve so far not found any of them to cause issues:

- Being public and static, anything could mess with the delegates, eg: unhooking other listeners by accident. This would usually be a) very obvious and b) very easy to fix, though.
- You can’t have non-terminating event loops, ie: Event A causes Event B causes Event A… ad infinitum. From the nature of the way I use the events this can’t really happen, and if it did I’d suggest there may be a design issue anyway, but it’s something to keep in mind because there could be cases where it’s an issue that I just haven’t run into yet.
- You need to be pretty good with hooking up and unhooking of those delegates. I stick to a few simple conventions about when to hook up and unhook and they’ve kept me out of trouble so far.

Anyway, with that in place it’s pretty rare that I ever need a singleton or similar construct. For instance, rather than having a “Pause” button that calls a function on a “GameManager” singleton, I have a “Pause” button that fires an event “PauseRequested”. Everything that needs to somehow respond to the game being paused is subscribed to that event and therefore has an appropriate method called. A pause is clearly pretty simple, but it doesn’t get much more complex than that even for stuff that might have taken quite a lot of code in a centralised manager. I think that the most complex I’ve had so far is having distinct “EventXYZStarted” and “EventXYZCompleted” events for stuff that takes time or that causes a state change which, so that receivers can respond at the start or the end as is appropriate.

As an added benefit, this has made code I’ve written that way super reusable. Nothing is tied to unrelated stuff via a singleton, and there are no singletons that are tied to each other. Each “role” encapsulates its own responsibilities and is only loosely coupled outside of that. So if I wan’t to reuse something in a different project I just copy the code files, copy some event delegate declarations, and then fire appropriate events from within the new project.

---

<div class="post-metadata">

**Author:** ![BFGames](https://avatars.discourse-cdn.com/v4/letter/b/34f0e0/32.png) [@BFGames](https://discussions.unity.com/u/BFGames)\
**Post date:** [September 19, 2013, 2:12am UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/15 "2013-09-19T02:12:22Z")

</div>

> [@cregox](#):
>
> So you both should definitely check out the wiki singleton I’ve already linked. Here again: [http://wiki.unity3d.com/index.php/Singleton](http://wiki.unity3d.com/index.php/Singleton)

If you only use “things” the way people tell you to use them on a web page or in a book, then thats up to you.  
Singletons is an easy and wonderful way to create and use game controllers.

The other day i used an image Technic to create a PGC dungeon system, it works wonderful and is fast. Was it meant to be used to generate levels? No, did it work? Perfectly.

---

<div class="post-metadata">

**Author:** ![cregox](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cregox/32/372683_2.png) [@cregox](https://discussions.unity.com/u/cregox)\
**Post date:** [September 19, 2013, 2:24pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/16 "2013-09-19T14:24:29Z")

</div>

> [@BFGames](#):
>
> If you only use “things” the way people tell you to use them on a web page or in a book, then thats up to you.  
> Singletons is an easy and wonderful way to create and use game controllers.
> 
> The other day i used an image Technic to create a PGC dungeon system, it works wonderful and is fast. Was it meant to be used to generate levels? No, did it work? Perfectly.

This only tells me you haven’t really checked out the link. I wrote it. And it’s not meant to be only “used”. It’s meant to be studied, used and reviewed. In **any case** there is nothing wrong with “only using things the way people tell you”. Repeating and following is first thing you do while learning.

@Errorsatz that’s not for “pure” singletons. It’s not pure at all. There’s even a warning on the very top saying 1 thing it should do, but doesn’t. I’ve branched out of it to make it work “per scene”. All it takes is removing the _“DontDestroyOnLoad”_ there. As with @BFGames, I don’t think you really read the wiki.

@fire7side using static for global vars is bad. You don’t need a big project to see why, just a complex one. Eventually errors will occur and it will be static’s fault.

@angrypenguin I’m not sure I understand what you’re doing, but seems like you’re trying to use a scheme to solve all your communication issues. Events are great and have its usage. Manager and singletons is complementary, not substitute to each other. Sending a broadcast message to all components warning about a Pause event is a good practice indeed. But you’ll need a keyboard listener to trigger that. There comes the singleton. In this case it could be a scene singleton, but if you have many levels in different scenes you may want to have that singleton as a DontDestroyOnLoad making it a more “pure” one. It’s not the only way to implement the trigger listener, but it is a good way never the less.

And God, all this just makes me remember how I hate forums. I didn’t came here to discuss. Just wanted to promote what’s already written. People in forums tend to not take careful reading, and I’m including myself there. Maybe if I read all posts before mine I’d realize this might be a bad thread to me to do what I did. So, I’m out of here now. Sorry if I bothered anyone. Peace. 😉

---

<div class="post-metadata">

**Author:** ![fire7side](https://avatars.discourse-cdn.com/v4/letter/f/a88e57/32.png) [@fire7side](https://discussions.unity.com/u/fire7side)\
**Post date:** [September 19, 2013, 4:19pm UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/17 "2013-09-19T16:19:16Z")

</div>

> [@](#):
>
> @fire7side using static for global vars is bad. You don’t need a big project to see why, just a complex one. Eventually errors will occur and it will be static’s fault.

There might be a problem if using threads, but Unity doesn’t recommend it. Other than that, it would just be sloppy programming and no different than misusing a public variable as far as I can see, and Unity makes a practice of that even though it’s not really recommended OO procedure. Why exactly do you believe that? Globals seem quite handy to me. I haven’t had any problems with them and I use them all the time. I don’t overuse them. I think they should be concentrated in one class, and please don’t tell me to read your link. Specific answers are for forums unless a person is searching for a reference. static is a keyword that specifies one instance, that’s it. Why does that cause errors? Or rather, more errors than a class that requires one instance that isn’t static. Both do add risks.  
I think an object that doesn’t destroy on load that is neither one might be what I use in the future.

---

<div class="post-metadata">

**Author:** ![andymads](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/andymads/32/120672_2.png) [@andymads](https://discussions.unity.com/u/andymads)\
**Post date:** [September 20, 2013, 11:21am UTC](https://discussions.unity.com/t/static-class-or-singleton/457184/18 "2013-09-20T11:21:46Z")

</div>

Like others, I use private static ‘instance’ fields for systems that I know exist only once in the project, with a public property for access. I don’t bother with reference counts. These systems always derive from MonoBehaviour so I can add them to a GameObject and make use of the benefits.
