-
Notifications
You must be signed in to change notification settings - Fork 0
/
MonoSingleton.cs
78 lines (66 loc) · 2.35 KB
/
MonoSingleton.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
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - LinkedIn: https://www.linkedin.com/in/rimuru/
// - GitHub: https://github.com/RimuruDev
//
// **************************************************************** //
using UnityEngine;
namespace RimuruDev
{
[HelpURL("https://github.com/RimuruDev/MonoSingleton")]
public abstract class MonoSingleton<TComponent> : MonoBehaviour where TComponent : Component
{
private static volatile TComponent instance;
private static readonly object lockObject = new();
public static bool HasInstance => instance != null;
public static TComponent TryGetInstance() => HasInstance ? instance : null;
public static TComponent Instance
{
get
{
if (instance != null)
return instance;
lock (lockObject)
{
if (instance == null)
{
instance = FindObjectOfType<TComponent>();
if (instance == null)
{
var obj = new GameObject
{
name = $"[ === {typeof(TComponent).Name} === ]"
};
instance = obj.AddComponent<TComponent>();
}
}
return instance;
}
}
}
protected virtual void Awake() =>
InitializeSingleton();
protected virtual void InitializeSingleton()
{
if (!Application.isPlaying)
return;
lock (lockObject)
{
if (instance == null)
{
instance = this as TComponent;
transform.SetParent(null);
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Debug.LogError($"Another instance of {typeof(TComponent).Name} already exists. Destroying the duplicate.");
Destroy(gameObject);
}
}
}
}
}