Singleton.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. namespace Rokid.MRC
  5. {
  6. public abstract class Singleton<T> where T : class, new()
  7. {
  8. private static T instance;
  9. public static T Instance
  10. {
  11. get
  12. {
  13. if(instance == null)
  14. {
  15. instance = new T();
  16. }
  17. return instance;
  18. }
  19. }
  20. //private Singleton()
  21. //{
  22. //}
  23. public virtual void Init()
  24. {
  25. }
  26. public virtual void OnDestroy()
  27. {
  28. }
  29. }
  30. public class UnitySingleton<T> : MonoBehaviour
  31. where T : Component
  32. {
  33. private static T _instance;
  34. public static T Instance
  35. {
  36. get
  37. {
  38. if(_instance == null)
  39. {
  40. _instance = FindObjectOfType(typeof(T)) as T;
  41. if(_instance == null)
  42. {
  43. GameObject obj = new GameObject();
  44. //obj.hideFlags = HideFlags.HideAndDontSave;
  45. _instance = (T)obj.AddComponent(typeof(T));
  46. }
  47. }
  48. return _instance;
  49. }
  50. }
  51. public virtual void Awake()
  52. {
  53. DontDestroyOnLoad(this.gameObject);
  54. if(_instance == null)
  55. {
  56. _instance = this as T;
  57. }
  58. }
  59. }
  60. }