You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Use Singleton in Unity

Ben Liu
Ben Liu

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.

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp