Singleton is a common design pattern in programming, which keeps only one copy of a variable or object throughout the entire runtime of the program.
Create a Singleton is quite simple in Unity:
First create an empty game object in the hierarchy named SingletonExample, then create a C# script attached to it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonExample: MonoBehaviour {
public static SingletonExample sharedInstance;
void Awake() {
if (sharedInstance == null) {
sharedInstance = this;
} else {
Destroy(gameObject);
}
public void DoSomething() {
Debug.Log("do something");
}
}
To use:
SingletonExample.sharedInstance.DoSomething();
Singleton vs Static Class
Singleton class can implement interfaces, inherit from other classes and allow inheritance.
Static class cannot inherit other classes.
- Singleton Objects stored on heap while static class stored in stack.
- Singleton Objects can have constructor while Static Class cannot.
- Singleton Objects can dispose but not static class.
- Singleton Objects can clone but not with static class.