zoukankan      html  css  js  c++  java
  • 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;
    }

      

  • 相关阅读:
    回车与换行的区别
    C# 验证数字
    FCKeditor 2.6.6在ASP中的安装及配置方法分享--ZZ转载自网络
    关于Application.Lock…Application.Unlock有什么作用?
    关于Application.Lock和Lock(obj)
    C#解决Linq OrderBy() 失效的小技巧
    文件夹添加 IIS 应用程序池用户权限
    we7调用模板如何区分栏目页与详细页
    第二阶段冲刺(第十天)
    每周总结(第十六周)
  • 原文地址:https://www.cnblogs.com/litmin/p/8576823.html
Copyright © 2011-2022 走看看