Unity常用的设计模式

        总结学习的一些Unity常用的设计模式,还在不断学习补充中...


  1. 单例模式
    using UnityEngine;
    
    public class MonoSingleton: MonoBehaviour
    {
        protected static MonoSingleton s_Instance;
        public static MonoSingleton Instance => s_Instance;
    
        private void Awake()
        {
            if (s_Instance != null)
            {
                Destroy(gameObject);
            }
            else
            {
                s_Instance = this;
            }
        }
    
        private void OnDestroy()
        {
            if (s_Instance == this)
            {
                s_Instance = null;
            }
        }
    }

  2. 泛型单例模式
    using UnityEngine;
    
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        protected static T s_Instance;
    
        public static T Instance => s_Instance;
    
        public static bool IsInitiated => s_Instance != null;
    
        protected virtual void Awake()
        {
            if (s_Instance != null)
            {
                Destroy(gameObject);
            }
            else
            {
                s_Instance = (T) this;
            }
        }
    
        protected virtual void OnDestroy()
        {
            if (s_Instance == this)
            {
                s_Instance = null;
            }
        }
    }

  3. 观察者模式
  4. MVC模式
  5. 工厂模式
  6. 享元模式

版权声明:本文为weixin_42039699原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。