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.
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 class can implement interfaces, inherit from other classes and allow inheritance.
Static class cannot inherit other classes.
Join the newsletter to receive the latest updates in your inbox.