Unity 轻量级对象池管理器(下)

需要查看有关该对象池的解析的,请跳转:

Unity 轻量级对象池管理器(上)

Unity 轻量级对象池管理器(下)_第1张图片

上图右下角的ObjectPool文件夹中,主要实现了两个脚本,第一个是对象池管理器(ObjectPoolManager),第二个是对象队列管理(ObjectPoolModel)

使用时只需要将ObjectPoolManager挂载在游戏场景中的某个对象中,并在场景中添加一个GameObjectPool空对象即可

ObjectPoolModel代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ObjectPool
{
    public class ObjectPoolModel
    {
        //未使用的对象
        //在场景中删除的对象暂存在这
        private Queue> unUsedList;

        public ObjectPoolModel()
        {
            unUsedList = new Queue>();
        }
        
        /// 
        /// 尝试获取未被使用的对象
        /// 
        /// 
        /// 
        public ObjectPoolItem TryGetUnUsedObject(ObjectType type)
        {
            if(unUsedList.Count != 0)
            {
                return unUsedList.Dequeue();
            }else
            {
                return null;
            }
        }

        public void AddUnUsedObject(T obj)
        {
            unUsedList.Enqueue(new ObjectPoolItem(obj));
        }
        /// 
        /// 删除队尾元素
        /// 
        public T UnUsedListDequeue()
        {
            ObjectPoolItem it =  unUsedList.Dequeue();
            
            return it.item;
        }
        /// 
        /// 清空对象池
        /// 
        public void ClearObjectPool()
        {
            this.unUsedList.Clear();
        }
        /// 
        /// 获取队列item数量
        /// 
        /// 
        public int TryGetQueueCount()
        {
            return unUsedList.Count;
        }
    }
    public class ObjectPoolItem
    {
        public T item;
        public bool isUsing;
        public ObjectPoolItem(T item)
        {
            this.item = item;
            isUsing = true;
        }
    }
}

ObjectPoolManager代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace ObjectPool
{
    /// 
    /// 针对一些大量重复的对象进行对象池管理,如僵尸,子弹等
    /// 
    public class ObjectPoolManager : MonoBehaviour
    {
        private static ObjectPoolManager _instance = null;
        public static ObjectPoolManager Instance
        {
            get
            {
                if(_instance == null)
                {
                    Debug.Log("创建单例模式");
                    _instance = GameObject.Find("GameLoop").GetComponent();
                    return _instance;
                }
                else
                {
                    //Debug.Log("调用单例模式");
                    return _instance;
                }
            }
        }
        private void Awake()
        {
            EventSys.LiteEventManager.Instance.Register(Base.ScenceLoadType.SceneChange, InitPool);
            _instance = this;
        }
        private void Start()
        {
        }
        /// 
        /// 初始化对象池
        /// 
        /// 
        private bool isInit = false;
        public void InitPool(object obj)
        {
            if((Base.ScenceType)obj == Base.ScenceType.BattleScene || (Base.ScenceType)obj == Base.ScenceType.NetWorkScene)
            {
                Debug.Log("初始化对象池");
                objectPools = new Dictionary>();
                pool = GameObject.Find("GameObjectPool");
                Debug.Log(pool.name);
                isInit = true;
            }
        }
        private Dictionary> objectPools;

        private bool lockObjectPools = false;

        private bool isClearing = false;

        //对象池中的对象统一挂载在Pool中
        private GameObject pool;
        /// 
        /// 从缓存池得到对象,得不到就实例化一个prefab
        /// 
        /// 
        /// 
        public GameObject GetObject(ObjectType type)
        {
            //先把objectPools锁起来,防止协程占用
            lockObjectPools = true;
            GameObject returnObj = null;
            if(objectPools.ContainsKey(type))
            {
                ObjectPoolModel pool = objectPools[type];
                ObjectPoolItem it = pool.TryGetUnUsedObject(type);
                if(it != null)
                {
                    returnObj = it.item;
                }
                else
                {
                    returnObj = ResManager.Instance.LoadPrefab(type);
                }
            }
            //如果没有创建这个对象池
            else
            {
                ObjectPoolModel pool = new ObjectPoolModel();
                objectPools.Add(type, pool);
                returnObj = ResManager.Instance.LoadPrefab(type);
            }
            //解锁
            returnObj.SetActive(true);
            lockObjectPools = false;
            return returnObj;
        }

        /// 
        /// 对象释放,并存入对象池中
        /// 
        /// 
        /// 
        public void Release(GameObject obj,ObjectType type)
        {
            //加锁
            lockObjectPools = true;
            if (objectPools.ContainsKey(type))
            {
                ObjectPoolModel pool = objectPools[type];
                pool.AddUnUsedObject(obj);
            }
            //如果没有创建这个对象池
            else
            {
                ObjectPoolModel pool = new ObjectPoolModel();
                objectPools.Add(type, pool);
                pool.AddUnUsedObject(obj);
            }
            //挂载到pool中
            obj.transform.SetParent(pool.transform);
            obj.SetActive(false);
            //解锁
            lockObjectPools = false;

        }

        IEnumerator ClearUnUsedObject()
        {
            isClearing = true;
            //每一秒清理一次
            yield return new WaitForSeconds(2);
            isClearing = false;
        }
        // Update is called once per frame
        void Update()
        {
            //定时清理缓存
            if(isInit == true && lockObjectPools == false&&isClearing == false)
            {
                foreach(var key in objectPools.Keys)
                {
                    if(objectPools[key].TryGetQueueCount()>0)
                    {
                        var obj = objectPools[key].UnUsedListDequeue();
                        //彻底销毁对象
                        GameObject.Destroy(obj.gameObject);
                    }
                }
                StartCoroutine(ClearUnUsedObject());
            }
        }
    }

    public enum ObjectType
    {
        Zombie_1,
        Zombie_2,
        ZombieBoss,
        Bullet,
        Equip,
        Guns,
        fireWork,
        fireBall,
        HurtText
        //Handle_CZ,
        //Handle_ZJ,
        //Scope_2,
        //Silencer_01,
        //Stock_05

    }
}

 

你可能感兴趣的:(Unity,轻量级游戏框架,Unity,TPS游戏设计)