Tanoda
pb_MonoBehaviourSingleton.cs
Go to the documentation of this file.
1using UnityEngine;
2
3namespace GILES
4{
8 public class pb_MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviour
9 {
11 private static MonoBehaviour _instance;
12
14 public virtual bool dontDestroyOnLoad { get { return false; } }
15
21 protected virtual void Initialize() {}
22
27 public static T instance
28 {
29 get
30 {
31 if(_instance == null)
32 {
33 // first search the scene for an instance
34 T[] scene = FindObjectsOfType<T>();
35
36 if(scene != null && scene.Length > 0)
37 {
38 _instance = scene[0];
39
40 for(int i = 1; i < scene.Length; i++)
41 {
42 pb_ObjectUtility.Destroy(scene[i]);
43 }
44 }
45 else
46 {
47 GameObject go = new GameObject();
48 string type_name = typeof(T).ToString();
49 int i = type_name.LastIndexOf('.') + 1;
50 go.name = (i > 0 ? type_name.Substring(i) : type_name) + " Singleton";
51 T inst = go.AddComponent<T>();
53 if(cast != null) cast.Initialize();
54 _instance = (MonoBehaviour) inst;
55 }
56
58 Object.DontDestroyOnLoad(_instance.gameObject);
59 }
60
61 return (T) _instance;
62 }
63 }
64
68 public static T nullableInstance
69 {
70 get { return (T) _instance; }
71 }
72
76 protected virtual void Awake()
77 {
78 if(_instance == null)
79 {
80 _instance = this;
81
83 Object.DontDestroyOnLoad(_instance.gameObject);
84 }
85 else
86 {
87 pb_ObjectUtility.Destroy(this.gameObject);
88 }
89 }
90 }
91}
virtual bool dontDestroyOnLoad
Override to maintain an instance of this object across level loads.
UnityEngine.Object Object