-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSingleBehaviour.cs
More file actions
96 lines (80 loc) · 2.45 KB
/
SingleBehaviour.cs
File metadata and controls
96 lines (80 loc) · 2.45 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using OlegHcp.Engine;
using OlegHcp.Tools;
using UnityEngine;
namespace OlegHcp.SingleScripts
{
/// <summary>
/// Represents implementation of MonoBehaviour singleton. It has no dynamic creation of an instance.
/// It should be saved in scene or should be created manually in runtime.
/// </summary>
public abstract class SingleBehaviour<T> : MonoBehaviour, IDisposable where T : SingleBehaviour<T>
{
private static T _instance;
private bool _locked;
/// <summary>
/// Static instance of SingleBehaviour`1.
/// </summary>
public static T I
{
get
{
if (_instance == null)
{
#if UNITY_2023_1_OR_NEWER
T instance = FindAnyObjectByType<T>(FindObjectsInactive.Include);
#elif UNITY_2020_1_OR_NEWER
T instance = FindObjectOfType<T>(true);
#else
T instance = FindObjectOfType<T>();
#endif
if (instance == null)
throw new ObjectNotFoundException(typeof(T));
if (instance._locked)
throw new InvalidOperationException($"The instance of {typeof(T).Name} is being configured. Avoid recursive calls.");
instance.Initialize();
}
return _instance;
}
}
/// <summary>
/// Returns true if the instance is not null.
/// </summary>
public static bool Exists => _instance != null;
private void Awake()
{
if (_instance != null)
{
if (this != _instance)
DebugErrors.MultipleInstancesMessage<T>();
return;
}
Initialize();
}
private void OnDestroy()
{
_instance = null;
Destruct();
}
public void Dispose()
{
gameObject.Destroy();
_instance = null;
}
private void Initialize()
{
_locked = true;
Construct();
_instance = this as T;
_locked = false;
}
/// <summary>
/// Used it instead of Awake.
/// </summary>
protected abstract void Construct();
/// <summary>
/// Used it instead of OnDestroy.
/// </summary>
protected abstract void Destruct();
}
}