Advertisement
yoav_tc

Singleton Class

Jan 16th, 2025
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.97 KB | Source Code | 0 0
  1. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  2. {
  3.     private static T _instance;
  4.  
  5.     public static T Instance
  6.     {
  7.         get
  8.         {
  9.             if (_instance == null)
  10.             {
  11.                 _instance = FindFirstObjectByType<T>();
  12.  
  13.                 if (_instance == null)
  14.                 {
  15.                     GameObject singletonObject = new GameObject(typeof(T).Name);
  16.                     _instance = singletonObject.AddComponent<T>();
  17.                 }
  18.             }
  19.  
  20.             return _instance;
  21.         }
  22.     }
  23.  
  24.     protected virtual void Awake()
  25.     {
  26.         if (_instance != null && _instance != this)
  27.         {
  28.             // If an instance already exists, destroy this new instance
  29.             Destroy(gameObject);
  30.             return;
  31.         }
  32.  
  33.         // This is the first instance or the assigned instance, don't destroy it on scene load
  34.         _instance = this as T;
  35.         //DontDestroyOnLoad(gameObject);
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement