Unity 单例模式

  单例模式是对象的创建模式之一,保证一个类仅有一个实例,并提供一个访问它的全局访问点。

  在什么情况下使用单例:

  1,一些管理器类。比如声音管理器、场景管理器、用户管理器等,

  2,一些辅助函数。

  Unity中单例实现分为两种,一种是继承自monobehavior的单例,另一种是普通的单例,这里不考虑多线程的使用,在创建单例是严格按照一定的次序创建,再按照相反的次序销毁。

  继承自monobehavior的单例:

  普通单例:

  

using System;

public class Singleton<T> where T : new()
{
    public static T instance
    {
        get
        {
            return Singleton<T>._GetInstance();
        }
    }

    public static bool exists
    {
        get
        {
            return !object.Equals(Singleton<T>._instance, default(T));
        }
    }

    private static T _GetInstance()
    {
        if (object.Equals(Singleton<T>._instance, default(T)))
        {
            Singleton<T>._instance = Activator.CreateInstance<T>();
        }
        return Singleton<T>._instance;
    }

    protected static T _instance;
}

  Monobehavior单例:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviourSingleton<T>
{
    public static T instance
    {
        get
        {
            return _GetInstance();
        }
    }

    private static T _GetInstance()
    {
        if(_instance == null)
        {
            _instance = FindObjectOfType(typeof(T)) as T;
            if(_instance == null)
            {
                GameObject obj = new GameObject();
                //obj.hideFlags = HideFlags.HideAndDontSave;
                _instance = (T)obj.AddComponent(typeof(T));
                DontDestroyOnLoad(obj);
            }
        }
        return _instance;
    }

    protected virtual void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
        if (_instance == null)
        {
            _instance = this as T;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    protected static T _instance;
}

 

  

posted @ 2018-03-23 12:34  Litmin  阅读(349)  评论(0编辑  收藏  举报