public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T instance;
public static T Instance
{
get
{
return instance;
}
}
/// <summary>
/// Returns whether the instance has been initialized or not.
/// </summary>
public static bool IsInitialized
{
get
{
return instance != null;
}
}
/// <summary>
/// Base awake method that sets the singleton's unique instance.
/// </summary>
protected virtual void Awake()
{
if (instance != null)
{
Debug.LogErrorFormat("Trying to instantiate a second instance of singleton class {0}", GetType().Name);
}
else
{
instance = (T) this;
}
}
protected virtual void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
}
如何使用
public class xxx: Singleton<xxx>
本文介绍了一种使用C#实现泛型单例模式的方法。通过定义一个泛型基类`Singleton<T>`,确保在整个应用程序中仅创建一次实例,并提供了初始化检查和对象销毁时清理实例的功能。适用于Unity等游戏开发环境。
1万+

被折叠的 条评论
为什么被折叠?



