Unity3D中实现一个简单的对象池?

我们通常在项目中,如果说引用了大量的同种预制体但是如子弹等有一定生命周期的,我们就可以使用对象池来做一些基本的简单优化。


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

namespace D_Bug{
    
    
   
	public class GameObjectPoolTwo : MonoBehaviour
	{
    
    
        #region Variables
        public static GameObjectPoolTwo Instance;       //懒人单例
        private Transform _allPoolDataParent = null;    //所有对象池的父物体
        private void Awake()
        {
    
    
            Instance = this;
            //创建对象池存父物体
            _allPoolDataParent = new GameObject("GameObjectPool").transform;
        }
        #endregion

        private Dictionary<string, OnePoolData> _objectPool = new Dictionary<string, OnePoolData>();

        //通过物体名字(地址)物体放入池子内
        public void ReleaseItem(GameObject item)
        {
    
    
            if (!_objectPool.ContainsKey(item.name))
            {
    
    
                CreateOneDataPool(_allPoolDataParent, item.name);
            }
            _objectPool[item.name].Pool.Release(item);
        }
        //通过名字(地址)获取池子内的物体
        public GameObject GetItem(string itemName)
        {
    
    
            if (!_objectPool.ContainsKey(itemName))
            {
    
    
                CreateOneDataPool(_allPoolDataParent, itemName);
            }
            return _objectPool[itemName].Pool.Get();
        }
        //创建一个小池子
        public void CreateOneDataPool(Transform allPoolParent,string itenName)
        {
    
    
            _objectPool.Add(itenName, new OnePoolData(allPoolParent, itenName));
        }
        //清空池子
        public void Clear()
        {
    
    
            _objectPool.Clear();
        }
    }
    //每一个小池子
    public class OnePoolData
    {
    
    
        public ObjectPool<GameObject> Pool;
        private Transform _smallPoolParent;
        private string _itemPath;

        public OnePoolData(Transform allPoolParent,string itemName)
        {
    
    
            _smallPoolParent = new GameObject(itemName).transform;
            _smallPoolParent.SetParent(allPoolParent);
            _itemPath = itemName;

            Pool = new ObjectPool<GameObject>(Create, Get, Release, null, true, 20, 100);
        }
        //创建资源
        private GameObject Create()
        {
    
    
            GameObject item = GameObject.Instantiate(Resources.Load<GameObject>(_itemPath));
            item.name = _itemPath;
            return item;
        }
        private void Get(GameObject obj)
        {
    
    
            obj.SetActive(true);
        }
        private void Release(GameObject obj)
        {
    
    
            obj.SetActive(false);
            obj.transform.SetParent(_smallPoolParent);
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_30163099/article/details/126474358