-
Notifications
You must be signed in to change notification settings - Fork 0
/
Singleton.cs
83 lines (70 loc) · 1.85 KB
/
Singleton.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using JetBrains.Annotations;
using UnityEngine;
namespace TinyMatter.Core {
public abstract class Singleton<T> : Singleton where T : MonoBehaviour
{
#region Fields
[CanBeNull]
private static T _instance;
[NotNull]
// ReSharper disable once StaticMemberInGenericType
private static readonly object Lock = new object();
[SerializeField]
private bool _persistent = true;
#endregion
#region Properties
[NotNull]
public static T Instance
{
get
{
if (Quitting)
{
// ReSharper disable once AssignNullToNotNullAttribute
return null;
}
lock (Lock)
{
if (_instance != null)
return _instance;
var instances = FindObjectsOfType<T>();
var count = instances.Length;
if (count > 0)
{
if (count == 1) {
return _instance = instances[0];
}
for (var i = 1; i < instances.Length; i++) {
Destroy(instances[i]);
}
return _instance = instances[0];
}
return _instance = new GameObject($"({nameof(Singleton)}){typeof(T)}").AddComponent<T>();
}
}
}
#endregion
#region Methods
private void Awake()
{
if (_persistent)
DontDestroyOnLoad(gameObject);
OnAwake();
}
protected virtual void OnAwake() { }
#endregion
}
public abstract class Singleton : MonoBehaviour
{
#region Properties
public static bool Quitting { get; private set; }
#endregion
#region Methods
private void OnApplicationQuit()
{
Quitting = true;
}
#endregion
}
//Free candy!
}