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

      

  • 相关阅读:
    2020去奔跑
    2020前两个月学习心得
    2020年1_2月寒假学习心得
    寒假中期考核个人总结
    Numpy、Matplotlib和pandas学习路线引导
    Python学习路线引导-Python入门基础
    2019在路上
    2020/11/28助教一周小结(第九周)
    2020/11/3助教一周小结(第五周)
    2020/10/25助教一周小结(第四周)
  • 原文地址:https://www.cnblogs.com/litmin/p/8576823.html
Copyright © 2020-2023  润新知