-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleton.cs
More file actions
34 lines (30 loc) · 1.03 KB
/
Singleton.cs
File metadata and controls
34 lines (30 loc) · 1.03 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
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
// Looks for an instance of T in the Object space
// If found, that instance is used.
// Otherwise, it will create a new instance.
_instance = (T)FindObjectOfType(typeof(T));
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) " + typeof(T).ToString();
DontDestroyOnLoad(singleton);
}
}
return _instance;
}
}
}
}