public class CylSingleton<T> where T : CylSingleton<T>, new()
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
Initialize();
}
return _instance;
}
}
public static bool HasInstance => _instance != null;
public static void Initialize()
{
if (_instance == null)
{
_instance = new T();
_instance.OnInitialize();
}
}
public static void Destroy()
{
if (_instance != null)
{
_instance.OnUnInitialize();
_instance = null;
}
}
protected virtual void OnInitialize() {}
protected virtual void OnUnInitialize() {}
}
public class ExposedSingleton<T> : MonoBehaviour where T : ExposedSingleton<T>
{
protected static T _instance;
public static T Instance => _instance;
public static bool HasInstance => _instance;
public static void Destroy()
{
if (_instance != null)
{
GameObject.Destroy(_instance.gameObject);
_instance = null;
}
}
}
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
protected static T _instance;
public static T Instance
{
get
{
if(_instance == null)
{
CreateInstance();
}
return _instance;
}
}
public static bool HasInstance => _instance;
public static void CreateInstance()
{
if (_instance) return;
var obj = new GameObject(typeof(T).Name);
_instance = obj.AddComponent<T>();
if (!Application.isPlaying)
{
obj.hideFlags = HideFlags.HideAndDontSave;
}
if (Application.isPlaying)
{
DontDestroyOnLoad(_instance);
}
}
public static void Destroy()
{
if (_instance != null)
{
GameObject.Destroy(_instance.gameObject);
_instance = null;
}
}
单例模式实例
于 2023-04-06 12:14:10 首次发布