-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleton.cs
58 lines (49 loc) · 1.53 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
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Singletons
{
/// <summary>
/// Used for <see cref="MonoBehaviour"/>.
/// </summary>
/// <remarks>By default the instance is only active in the scene where it was created. To persist the instance over multiple scene loads call <see cref="DontDestroyOnLoad"/>.</remarks>
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
protected static T instance;
private bool keep;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<T>();
if (instance == null)
Debug.LogError($"The singleton ({typeof(T).Name}) you were trying to access was not part of the scene! Add the component to a game object in the scene and try again.");
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
{
instance = this as T;
SceneManager.sceneUnloaded += OnSceneUnloaded;
}
else
{
Destroy(gameObject);
}
}
private void OnSceneUnloaded(Scene scene)
{
if (!keep)
instance = null;
}
protected void DontDestroyOnLoad()
{
DontDestroyOnLoad(gameObject);
keep = true;
}
}
}