C#

Use Singleton in Unity

ยท 1 min read
Use Singleton in Unity

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.

  1. Singleton Objects stored on heap while static class stored in stack.
  2. Singleton Objects can have constructor while Static Class cannot.
  3. Singleton Objects can dispose but not static class.
  4. Singleton Objects can clone but not with static class.