-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSingleScript.cs
More file actions
91 lines (75 loc) · 2.19 KB
/
SingleScript.cs
File metadata and controls
91 lines (75 loc) · 2.19 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
using System;
using OlegHcp.Tools;
using UnityEngine;
namespace OlegHcp.SingleScripts
{
public abstract class SingleScript<T> : ScriptableObject where T : SingleScript<T>
{
private static T _instance;
private bool _locked;
/// <summary>
/// Static instance of SingleScript`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 OnEnable()
{
if (_instance != null)
{
if (this != _instance)
DebugErrors.MultipleInstancesMessage<T>();
return;
}
Initialize();
}
private void OnDisable()
{
_instance = null;
Destruct();
}
public void Dispose()
{
Destroy(this);
_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();
}
}