Singleton.cs 567 B

1234567891011121314151617181920
  1. using System;
  2. using UnityEngine;
  3. namespace SchoenLogger
  4. {
  5. public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  6. {
  7. private static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton);
  8. public static T Instance => LazyInstance.Value;
  9. private static T CreateSingleton()
  10. {
  11. var ownerObject = new GameObject($"{typeof(T).Name} (singleton)");
  12. var instance = ownerObject.AddComponent<T>();
  13. DontDestroyOnLoad(ownerObject);
  14. return instance;
  15. }
  16. }
  17. }