-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton-pattern.cs
More file actions
60 lines (52 loc) · 1.62 KB
/
singleton-pattern.cs
File metadata and controls
60 lines (52 loc) · 1.62 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
// Unity Singleton Pattern
// Use for managers that need exactly one instance (AudioManager, GameManager).
// Survives scene loads. Self-creates if missing.
// Uses FindFirstObjectByType (not the deprecated FindObjectOfType).
using UnityEngine;
namespace MyGame
{
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static readonly object _lock = new();
private static bool _applicationIsQuitting;
public static T Instance
{
get
{
if (_applicationIsQuitting)
return null;
lock (_lock)
{
if (_instance == null)
{
_instance = FindFirstObjectByType<T>();
if (_instance == null)
{
var singletonObject = new GameObject(typeof(T).Name);
_instance = singletonObject.AddComponent<T>();
DontDestroyOnLoad(singletonObject);
}
}
return _instance;
}
}
}
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (_instance != this)
{
Destroy(gameObject);
}
}
private void OnApplicationQuit()
{
_applicationIsQuitting = true;
}
}
}