-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingletonMono.cs
72 lines (66 loc) · 1.99 KB
/
SingletonMono.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
using UnityEngine;
using Debug = System.Diagnostics.Debug;
namespace Cnoom.UnityTool.SingletonUtils
{
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour, ISingleton where T : SingletonMonoBehaviour<T>
{
private static T instance;
private static readonly object Lock = new object();
private ISingletonMono singletonMonoImplementation;
public abstract bool IsDestroyOnLoad { get; }
public static T Instance
{
get
{
if(instance == null)
{
lock (Lock)
{
if(instance == null)
{
instance = FindAnyObjectByType<T>();
if(instance == null)
{
GameObject singleton = new GameObject();
instance = singleton.AddComponent<T>();
singleton.name = typeof(T).Name + " (Singleton)";
}
}
}
}
return instance;
}
}
protected virtual void Awake()
{
if(instance != null && instance != this)
{
Destroy(gameObject);
}
else
{
instance = this as T;
Debug.Assert(instance != null, nameof(instance) + " != null");
instance.OnSingletonInit();
if(!IsDestroyOnLoad)
{
DontDestroyOnLoad(instance);
}
}
}
protected virtual void OnDestroy()
{
if(instance == this)
{
Dispose();
}
}
public virtual void Dispose()
{
instance = null;
}
public virtual void OnSingletonInit()
{
}
}
}