Попалась такая вот реализация синглтона в одной Unity-игре.
Камрады, вы можете предположить - для чего оно нужно?
а) Если в типе T не определён ни один из методов жизненного цикла вроде Update.
б) Если определён.
Синтаксис:
Используется csharp
public class PersistenSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance
{
get
{
if (instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1)
{
DontDestroyOnLoad(instance.gameObject);
return instance;
}
if (instance == null)
{
GameObject gameObject = new GameObject(typeof(T).Name);
instance = gameObject.AddComponent<T>();
DontDestroyOnLoad(gameObject);
}
else
{
DontDestroyOnLoad(instance.gameObject);
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
return;
T[] array = FindObjectsOfType<T>();
if (array.Length <= 1)
return;
T[] array2 = array;
for (Int32 i = 0; i < array2.Length; i++)
{
T t = array2[i];
if (t != instance)
{
Destroy(t.gameObject);
}
}
}
private static T instance;
}
{
public static T Instance
{
get
{
if (instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1)
{
DontDestroyOnLoad(instance.gameObject);
return instance;
}
if (instance == null)
{
GameObject gameObject = new GameObject(typeof(T).Name);
instance = gameObject.AddComponent<T>();
DontDestroyOnLoad(gameObject);
}
else
{
DontDestroyOnLoad(instance.gameObject);
}
}
return instance;
}
}
protected virtual void Awake()
{
if (instance == null)
return;
T[] array = FindObjectsOfType<T>();
if (array.Length <= 1)
return;
T[] array2 = array;
for (Int32 i = 0; i < array2.Length; i++)
{
T t = array2[i];
if (t != instance)
{
Destroy(t.gameObject);
}
}
}
private static T instance;
}
Эта дрянь повышает связанность кода и тащит MonoBehaviour в те части, которые (по-моему мнению) в них не нуждаются.
Чем может грозить её замена обычным классом со статическим свойством и отложенной инициализацией?
Или всё это направлено исключительно для поддержки редактора, чтобы изменения отображались без перекомпиляции проекта?