Unity缓存池(对象池 Pool)

缓存池

缓存池简单理解就是预加载,预加载之后,先不激活物体

当需要实例化对象时,不优先使用Instantiate,首先去对象池(Pool)里查找,如果对象池(Pool)中有物体,就直接取出来一个

当需要销毁物体时,不会优先使用Destroy

首先去池子中判断池子是否达到最大容纳量,如果超出就Destroy,如果没有达到则放入池子并设置为false

案例一

using System.Collections.Generic;
using UnityEngine;

namespace Pool
{
    public class PoolTest : SingleCase<PoolTest>
    {
        private Queue<GameObject> _objPool;
        private Queue<GameObject> _activeObjs;
        private int _maxCount = 10;

        private void Awake()
        {
            _objPool = new Queue<GameObject>();
            _activeObjs = new Queue<GameObject>();
        }

        private void Start()
        {
            for (int i = 0; i < _maxCount; i++)
            {
                GameObject obj = CreateObj();
                _objPool.Enqueue(obj);
                obj.SetActive(false);
            }
        }

        public void GetOutObj()
        {
            if (_objPool.Count > 0)
            {
                GameObject obj = _objPool.Dequeue();
                _activeObjs.Enqueue(obj);
                obj.SetActive(true);
                return;
            }

            GameObject obj2 = CreateObj();
            _activeObjs.Enqueue(obj2);
        }

        public void PutToPool()
        {
            if (_activeObjs.Count > 0)
            {
                GameObject obj = _activeObjs.Dequeue();
                if (_objPool.Count < _maxCount)
                {
                    obj.SetActive(false);
                    _objPool.Enqueue(obj);
                }
                else
                {
                    Destroy(obj);
                }
            }
        }

        private GameObject CreateObj()
        {
            GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
            obj.transform.position = Vector3.zero;
            obj.AddComponent<Rigidbody>().GetComponent<Rigidbody>().isKinematic = true;
            return obj;
        }
    }
}
using UnityEngine;

namespace Pool
{
    public class TestTool : MonoBehaviour
    {
        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                PoolTest.Instance.GetOutObj();
            }

            if (Input.GetMouseButtonDown(1))
            {
                PoolTest.Instance.PutToPool();
            }
        }
    }
}
上一篇
下一篇