Interhaptics SDK for Unity 1.6
Loading...
Searching...
No Matches
Singleton.cs
Go to the documentation of this file.
1/* ​
2* Copyright (c) 2023 Go Touch VR SAS. All rights reserved. ​
3* ​
4*/
5
6using UnityEngine;
7
8
10{
11
12 public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
13 {
14
15 #region Fields
16 private static T _instance;
17
18 private static readonly object Lock = new object();
19
20 [SerializeField]
21 private bool _persistent = true;
22 #endregion
23
24 #region Properties
25 public static bool Quitting { get; private set; }
26
27 public static T Instance
28 {
29 get
30 {
31 if (Quitting)
32 {
33 Debug.LogWarning($"[Singleton<{typeof(T)}>] Instance will not be returned because the application is quitting.");
34 return null;
35 }
36 lock (Lock)
37 {
38 if (_instance != null)
39 {
40 return _instance;
41 }
42
43 var instances = FindObjectsOfType<T>();
44 var count = instances.Length;
45 if (count == 0)
46 {
47 Debug.Log($"[Singleton<{typeof(T)}>] An instance is needed in the scene and no existing instances were found, so a new instance will be created.");
48 return _instance = new GameObject($"(Singleton){typeof(T)}").AddComponent<T>();
49 }
50 if (count > 1)
51 {
52 Debug.LogWarning($"[Singleton<{typeof(T)}>] There should never be more than one Singleton of type {typeof(T)} in the scene, but {count} were found. The first instance found will be used, and all others will be destroyed.");
53 for (var i = 1; i < instances.Length; i++)
54 {
55 Destroy(instances[i]);
56 }
57 }
58
59 return _instance = instances[0];
60 }
61 }
62 }
63 #endregion
64
65 #region Methods
66 private void Awake()
67 {
68 if (_persistent)
69 {
70 var instances = FindObjectsOfType<T>();
71 if (instances.Length > 1)
72 {
73 Destroy(gameObject);
74 return;
75 }
76 else
77 {
78 DontDestroyOnLoad(gameObject);
79 }
80 }
81
82 OnAwake();
83 }
84
85 private void OnApplicationQuit()
86 {
87 Quitting = true;
89 }
90
91 protected virtual void OnAwake() { }
92
93 protected virtual void OnOnApplicationQuit() { }
94 #endregion
95
96 }
97
98}
virtual void OnOnApplicationQuit()
Definition Singleton.cs:93