游戏中很多管理类都需要写成单例类,每次重复把管理类设置为单例类很繁琐,
这里直接写一个泛型单例类作为模板父类,方便其他需要写成单例类的类直接继承设置为单例类;
using UnityEngine;public class Singleton<T> : MonoBehaviour where T:Singleton<T>
{private static T instance;public static T Instance{get { return instance; }}public static bool IsInitialized{get { return instance != null; }}protected virtual void Init(){if (instance != null) Destroy(gameObject);else instance = (T)this;}protected virtual void Destroy(){if (instance == this) instance = null;}
}
其他要写成单例类的类,可以直接继承Singleton,示例如下:
using UnityEngine;public class GameManager : Singleton<GameManager>
{protected override void Init(){base.Init();if (IsInitialized) Debug.Log("游戏初始化!");}
}