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

      

  • 相关阅读:
    Java基础-Object通用方法
    Java基础-关键字
    Java基础-运算
    Java基础-String
    Java基础-数据类型
    GCN-GAN:对加权动态网络的非线性时间链路预测模型
    长短期记忆(long short-term memory, LSTM)
    CSP 201604-1 折点计数
    介绍一个好东西C++11
    malloc free使用规范
  • 原文地址:https://www.cnblogs.com/litmin/p/8576823.html
Copyright © 2011-2022 走看看