Using the design pattern Singleton in your Unity3D project using C#

 

What is the Design Patter Singleton ?

Singleton is a design pattern (it's a general, reusable solution to a commonly occurring problem within a given context in software design) of the creation type that ensures that there will be a single instance for an object type. Such a pattern design can be useful in game development to guarantee unique instances of objects such as GameManager, Inventory, CoinManager and etc.

 

 

Example if a C# singleton in Unity3D 

 

public class GameManager : MonoBehavior {
    private static GameManager _instance;

    public static GameManager instance { get { return _instance; } }


    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);

        } else {
            
            _instance = this; 
             DontDestroyOnLoad(gameObject);
 } } }

 

 

Example of Singleton using Generics

The main advantage of using this type of implementation is that you won't have to implement Singleton in a class every time, just simply inherit that class.

using UnityEngine;

using UnityEngine;

public class Singleton : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
    public static bool dontDestriyOnLoadEnbled = false;
    public static T instance
    {
        get
        {

            if (_instance == null)
            {
                _instance = FindObjectOfType();

                 if (_instance != null && dontDestriyOnLoadEnbled)
                    DontDestroyOnLoad(_instance);
            }
           
            return _instance;
        }
    }
 

}

 

How to use the Singleton Generics 

 

public class Manager: Singleton <Manager> {
	 protected Manager () {} // guarantee this will be always the only singleton - can not use the constructor!

	 public string myGlobalVar = "whatever";
 } 

 

Singleton vs classes, methods and statics paramenters

It is possible to have a similar result of the Singleton design pattern by using static classes, methods and parameters, but there are some advantages of using Singleton such as:

1. Singleton allows you to use Inheritance while classes, methods and static parameters do not.

2. Singleton allows you to implement Interfaces.

 

If you are creating an adventure or rpg game consider prototyping it using this pack HERE



References:

https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm

http://wiki.unity3d.com/index.php/Singleton

https://github.com/Naphier/unity-design-patterns