1. 程式人生 > >Unity萬能單例框架

Unity萬能單例框架

1.0 需要掛載遊戲物件的單例類

 public abstract class SingletonBaseMono<T> : MonoBehaviour where T : SingletonBaseMono<T>
{
    protected static T _Instance = null;
    public static T Instance
    {
        get
        {
            if (null == _Instance)
            {
                //尋找是否存在當前單例類物件
GameObject go = GameObject.Find(typeof(T).Name); //不存在的話 if (go == null) { //new一個並新增一個單例指令碼 go = new GameObject(); _Instance = go.AddComponent<T>(); } else
{ if (go.GetComponent<T>() == null) { go.AddComponent<T>(); } _Instance = go.GetComponent<T>(); } //在切換場景的時候不要釋放這個物件 DontDestroyOnLoad(go); } return
_Instance; } } }

2.0 資料類單例

public class SingletonBase<T> where T : class ,new()
{
    private static T _instance=null;

    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }

    //構造的同時呼叫初始化函式
        protected SingletonBase()
        {
            if (null != _instance)
            Init();
        }

    public virtual void Init()
    {

    }
}