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 T instance;
10
11 private static readonly object lockObject = new object();
12
13 public static T Instance
14 {
15 get
16 {
18 {
19 Debug.LogWarning("[ApexSingleton] Singleton Instance '{0}' won't be created while application is quitting.");
20 return null;
21 }
22
23 lock (lockObject)
24 {
25 if (instance == null)
26 {
27#if UNITY_2020_1_OR_NEWER
28 Object[] existingInstances = FindObjectsByType<T>(FindObjectsSortMode.None);
29#else
30 Object[] existingInstances = FindObjectsOfType(typeof(T));
31#endif
32
33 if (existingInstances.Length <= 0)
34 {
35 GameObject singleton = new GameObject();
36 instance = singleton.AddComponent<T>();
37 instance.name = "Singleton_" + typeof(T).ToString();
38
39 DontDestroyOnLoad(instance);
40 return instance;
41 }
42
43 instance = existingInstances[0] as T;
44
45 if (existingInstances.Length > 1)
46 {
47 Debug.LogError("[ApexSingleton] Multiple instances of '{0}' found. There should only be 1 instances. Reopening the scene might fix the problem.");
48 return instance;
49 }
50
51 if (instance == null)
52 {
53 Debug.LogAssertion("[ApexSingleton] An instance was found and is still null.");
54 return null;
55 }
56 }
57
58 return instance;
59 }
60 }
61 }
62
63 private static bool ApplicationIsQuitting = false;
72 public virtual void OnDestroy()
73 {
74 Debug.Log("[ApexSingleton] On Destroy on singleton called.");
76 }
77 }
78}
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