码迷,mamicode.com
首页 > 编程语言 > 详细

Unity 单例模式

时间:2018-03-23 14:09:01      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:ati   管理   static   bsp   rtu   virt   单例   实现   ons   

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

  在什么情况下使用单例:

  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;
}

 

  

Unity 单例模式

标签:ati   管理   static   bsp   rtu   virt   单例   实现   ons   

原文地址:https://www.cnblogs.com/litmin/p/8576823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!