hi.im trying to find the difference between singleton and static.i tried to find the answer online but i cant really understand it as my english is not very good.can someone use simple english to explain the difference between the two?when to use singleton and when to static?
Practically speaking for most of us, a static class can only have static members. It also can’t use an interface. You are probably better off just starting off using a singleton right away. They pretty much serve the same purpose. There are tutorials on youtube for singletons. You create a singleton and then make the object DontDestroyOnLoad and use it for a central location for managing your game and moving between scenes without losing information.
A static class (with its static methods and variables) is a language construct that allows you to use those methods and variables without the need to create an instance.
That means of course, that the static class will act as a Singleton (because its unique)
A Singleton is not a language feature, its a concept, a design pattern.
There are different ways to implement a Singleton. One of them is using static classes.
One of the benefits of implementing a Singleton without static classes is “homogeneity”: All classes must be instanced, the Singleton is just an instanced class but you only use that unique instance always. Also you can assign the instance to a variable if you need it.
Static class singleton example:
public static class Singleton {
public static String Variable1;
public static void Method1() {
}
}
//Singleton use
Singleton.Variable1 = "TEST";
Singleton.Method1();
NonStatic class singleton example
public class Singleton {
private static Singleton instance;
// This method always will return the same instance
public static Singleton GetInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// The constructor is private, the only way to obtain an instance is from GetInstance
private Singleton() {
}
public String Variable1;
public void Method1() {
}
}
// Singleton use
Singleton s = Singleton.GetInstance();
s.Variable1 = "Test";
s.Method1();
Like others have said, but in a different way (in case that helps).
A static class has no instance. A singleton is an instance of a class. Like any other class. A better question is what’s the difference between a singleton and a regular class. A singleton IS a regular class, there is actually no difference. It’s just that there is code written to do with that class that makes sure there’s only ever one instance of that class created. When another is created it’s automatically destroyed, and if there is no singleton existing yet, automatically create one. Unity loves using singletons as there’s no single point of entry to make a clear dependency graph from our perspective as regular game devs.
For me, the big deciding factor between Static and Singleton is whether I want the class to be a MonoBehaviour. You can make a singleton class that inherits from MonoBehaviour, but you can’t make a static class derive from MonoBehaviour. This means that if you want your class to participate in Unity’s event loop (Start/Update/OnXYZ, etc), you’d want a singleton instead of a static class.
I use static classes to hold constants and reusable methods. I use singletons when I want an object in my scene.
The last two lines of each code look similar in terms of concept yet I still don’t understand exactly why would someone prefer a singleton over a static class. I did not get your explanation. Can you explain more about the uses of a singleton with an example related to game? Thank you
Elaborating on my (pretty old now) post above, I think personally it comes down to two things: 1) Do I want MonoBehaviour functionality on the object? And 2) What is the lifecycle of the data I’m storing.
To the first point, a static class can hold data and it can have methods associated with it. However, it won’t “do” things regularly within the Unity event loop (https://docs.unity3d.com/Manual/ExecutionOrder.html). That is, a static class won’t perform Update() or FixedUpdate() calls, or any of the other things that come from being a MonoBehaviour. Many of my singletons do things regularly in Update(), so it makes sense for them to be Singletons instead of static classes.
The second point, regarding lifecycle, is a bit less defined. But in my case, I have some singletons that last from the time the game starts to the time the game exits. For these kinds of singletons, there’s only one of each, and they live forever. An example of this might be a singleton holding onto the player’s overall progress through the game. But I also have other singletons that have shorter lifespans, lasting only for the duration of a single scene. And example of that kind of singleton is one that I use to track the creation and destruction of all Rigidbodies in the scene. Once I switch to a new scene, that singleton is destroyed, and the new scene created a new singleton specific to that scene. I could, of course, make this a long-lived singleton like my other singletons, and just purge its data every time I change scenes. But it seemed simpler just to scope some of my singletons to scenes, and others to the whole game.
Anyway, if your class just has data and some methods that other classes call, feel free to make that a static class. I don’t make things into singletons unless they really need to be.
I find this question very interesting. Clearly, a static class avoid all the problems related to making sure that there is only one instance and, more importantly, that the instantiation (of the singleton) is thread-safe.
As @dgoyette points out, the lifecylce and the monobehaviour inheritance are the main distinguishing features.
Static classes, for good or for bad, are guaranteed to live from the beginning to the end of the program. While singletons’ lifecycles will depend on your implementation of scenes since they must be attached to game objects (else they are not executed). If you use some ``permanent’’ underlying scene and just load other scenes additively, you can have that a singleton in the permanent scene lives for all the game. This need to be attached and the difference in lifecylces arguably makes static classes more reliable for universal/global purposes, since you don’t have to worry about instantiation or destruction.
Static classes, however, cannot inherit from Monobehaviour because the inherited methods are not static. This is not as restrictive as it seems because you can relay those events/callbacks. To see this, use the next two scripts:
GameManager.cs
// Just put this script in your assets folder; don't attach it to a Game Object.
public static class GameManager
{
static int frameNumber = 0;
public static void CameraUpdateReceived()
{
Debug.Log("GameManager Script: Camera-update "+(frameNumber++)+" was received.");
}
}```
CameraUpdate.cs
using System;
using UnityEngine;
// Attach this script to the scene’s camera
public class CameraUpdate : MonoBehaviour
{
public event Action MyUpdate;
// Start is called before the first frame update
void Start()
{
MyUpdate += GameManager.CameraUpdateReceived;
}
// Update is called once per frame
void Update()
{
MyUpdate();
}
}
But more importantly, if you are not dealing with an object that has to be continually updated, a static class is more efficient because it won't be called every frame. I look forward to others' take on this subject.
It seems you’re overlooking a fairly important feature of “permanent” game object: DontDestroyOnLoad(). When this is called on a game object, it prevents that game object from being destroyed when changing scenes. As such, there’s no need for some complex additive-only scene loading approach to keep singletons alive. Just call DontDestroyOnLoad in the singleton’s start, and it won’t be destroyed by scene loading. This will more or less make the object permanent unless you explicitly destroy it for some reason.
With my DontDestroyOnLoad singletons, they basically all do something meaningful in their Update methods, so this is a much more convenient approach compared to splitting the singleton into a static class and a wrapper.