-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingletonPrefab.cs
54 lines (47 loc) · 1.66 KB
/
SingletonPrefab.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
using UnityEngine;
/// <summary>
/// SingletonPrefab allows you to call [Tname].Instance anywhere and have the
/// prefab instantiated at run-time if it does not already exist in the scene.
/// IMPORTANT: This only works if you have named your prefab the exact same name as the class name of T.
/// </summary>
public abstract class SingletonPrefab<T> : MonoBehaviour where T : MonoBehaviour {
public bool dontDestroyOnLoad = false;
public bool logSingleton = true;
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
Debug.Log ("[SingletonObj] Instantiating new " + typeof(T) + " instance.");
string n = typeof(T).Name;
_instance = Instantiate (Resources.Load<T> (n));
_instance.name = "[SingletonObj] " + n;
}
return _instance;
}
}
void Awake () {
if (_instance == null) {
_instance = this.GetComponent<T> ();
if (logSingleton)
Debug.Log("[SingletonObj] An instance of " + typeof(T) + " was found in the scene.", this);
}
else if (Instance.GetHashCode () != this.GetComponent<T> ().GetHashCode ()) {
if (logSingleton)
Debug.LogWarning ("[SingletonObj] Destroying duplicate instance of type " + typeof(T) + ".");
Destroy (this.gameObject);
return;
}
if (dontDestroyOnLoad) {
if (logSingleton)
Debug.Log ("[SingletonObj] Marking " + typeof(T) + " as DontDestroyOnLoad.", this);
DontDestroyOnLoad (this.gameObject);
}
}
void OnDestroy () {
if (_instance != null && _instance.GetHashCode () == this.GetComponent<T> ().GetHashCode ()) {
if (logSingleton)
Debug.Log ("[SingletonObj] Destroying main instance of " + typeof(T) + ".");
_instance = null;
}
}
}