16 private static T instance;
25 public static T Instance
29 if (!IsInitialized && searchForInstance)
31 searchForInstance =
false;
32 T[] objects = FindObjectsOfType<T>();
33 if (objects.Length == 1)
35 instance = objects[0];
36 instance.gameObject.GetParentRoot().DontDestroyOnLoad();
38 else if (objects.Length > 1)
40 Debug.LogErrorFormat(
"Expected exactly 1 {0} but found {1}.", typeof(T).Name, objects.Length);
47 private static bool searchForInstance =
true;
51 Debug.Assert(IsInitialized,
string.Format(
"The {0} singleton has not been initialized.", typeof(T).Name));
57 public static bool IsInitialized
61 return instance != null;
83 if (IsInitialized && instance !=
this)
85 if (Application.isEditor)
87 DestroyImmediate(
this);
94 Debug.LogErrorFormat(
"Trying to instantiate a second instance of singleton class {0}. Additional Instance was destroyed", GetType().Name);
96 else if (!IsInitialized)
99 searchForInstance =
false;
100 gameObject.GetParentRoot().DontDestroyOnLoad();
112 if (instance ==
this)
115 searchForInstance =
true;