Singleton : Implementation in Unity3d C#

Singleton : Implementation in Unity3d C#

F:http://www.unitygeek.com/unity_c_singleton/

Objective :

Singleton is a very complex topic, In this, we try to understand basics and various implementation of Singleton in Unity3d using C#.

Intro:

Singleton is a basic Design Pattern. Classes implementing Singleton pattern will ensure that only one instance of the object ever exists at any one time. It is recommend using Singletons for things that do not need to be copied multiple times during a game.This is great for controller classes like GameManager or AudioController.

Implementation:

There are several ways of implementing Singleton in Unity, we will some of the implementation in this tutorial

  1. Simplest Implementation
01
02
03
04
05
06
07
08
09
10
11
public class SingletonController : MonoBehaviour {
public static SingletonController instance;
 
   private void Awake() {
    if (instance != null) {
      Destroy(gameObject);
    } else {
      Instance = this;
    }
  }
}

Above code is the simplest implementation of Singleton, but there are some issues which we have to address

  1. Singleton is not persistent across the Unity scenes.
  2. All the executable code must be attached to GameObject in the hierarchy.
  3. It is not recommended to call SingletonController.Instance in any Awake() method because, since we don’t know the order that Awake() will be executed through all scripts, we can end up with a Null