Singleton

Open World - Scripts - Singleton

How to make a Singleton / Instance in Unity3D with C#

To make a Sigleton or Instanced class it just requires a file with jus seven lines as you will see below. The magic of the Singleton is all done with in this one line.

if (instance == null) { instance = GetComponent<T>(); }

Singleton.cs 327B


using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance = default;
    public static T Instance => instance;
    protected virtual void Awake()
    {
        if (instance == null) { instance = GetComponent<T>(); }
        else { Destroy(this); }
    }
}
Powered by w3.css