Documentation for the Unity C# Library
Loading...
Searching...
No Matches
ApexSingleton.cs
Go to the documentation of this file.
1using System.Collections;
2using System.Collections.Generic;
3using UnityEngine;
4
5namespace PixoVR.Apex
6{
7 public class ApexSingleton<T> : MonoBehaviour where T : MonoBehaviour
8 {
9 private static readonly string MASTER_TAG = "ApexSingleton";
10 private static T instance;
11
12 private static readonly object lockObject = new object();
13
14 public bool InitializeInstance(T targetInstance)
15 {
16 lock (lockObject)
17 {
18 if (instance == null)
19 {
20 instance = targetInstance;
21 DontDestroyOnLoad(instance);
22 return true;
23 }
24 else if(instance != targetInstance)
25 {
26 Debug.unityLogger.Log(LogType.Warning, MASTER_TAG, "Destroying an instance that was created after.");
27 Destroy(targetInstance.gameObject);
28 }
29 }
30
31 return false;
32 }
33
34 public static T Instance
35 {
36 get
37 {
39 {
40 Debug.unityLogger.Log(LogType.Warning, MASTER_TAG, "Singleton Instance '{0}' won't be created while application is quitting.");
41 return null;
42 }
43
44 lock (lockObject)
45 {
46 if (instance == null)
47 {
48#if UNITY_2020_1_OR_NEWER
49 Object[] existingInstances = FindObjectsByType<T>(FindObjectsSortMode.None);
50#else
51 Object[] existingInstances = FindObjectsOfType(typeof(T));
52#endif
53
54 if (existingInstances.Length <= 0)
55 {
56 GameObject singleton = new GameObject();
57 instance = singleton.AddComponent<T>();
58 instance.name = "Singleton_" + typeof(T).ToString();
59
60 DontDestroyOnLoad(instance);
61 return instance;
62 }
63
64 instance = existingInstances[0] as T;
65
66 if (existingInstances.Length > 1)
67 {
68 Debug.unityLogger.Log(LogType.Error, MASTER_TAG, "Multiple instances of '{0}' found. There should only be 1 instances. Reopening the scene might fix the problem.");
69 return instance;
70 }
71
72 if (instance == null)
73 {
74 Debug.unityLogger.Log(LogType.Assert, MASTER_TAG, "An instance was found and is still null.");
75 return null;
76 }
77 }
78
79 return instance;
80 }
81 }
82 }
83
84 private static bool ApplicationIsQuitting = false;
93 public virtual void OnDestroy()
94 {
95 Debug.unityLogger.Log(LogType.Log, MASTER_TAG, "On Destroy on singleton called.");
97 }
98 }
99}
virtual void OnDestroy()
When Unity quits, it destroys objects in a random order. In principle, a Singleton is only destroyed ...
static bool ApplicationIsQuitting
static readonly object lockObject
bool InitializeInstance(T targetInstance)
static readonly string MASTER_TAG