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;
}
}
文章来源地址https://www.toymoban.com/news/detail-408981.html
文章来源:https://www.toymoban.com/news/detail-408981.html
到了这里,关于单例模式实例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!