using System; using UnityEngine; using System.Collections.Generic; using UEObject = UnityEngine.Object; namespace BF { public interface IObjectPool { void Clear(); } public class ClassPool : IObjectPool where T : class { static ClassPool instance; public static ClassPool Create(int size = 100) { if (instance == null) instance = new ClassPool(size); return instance; } private ClassPool(int poolSize = 100) { PoolSize = poolSize; } Queue pool = new Queue(); public int PoolSize { get; private set; } public void SetPoolSize(int poolSize) { PoolSize = poolSize; } public T Get() { if (pool.Count > 0) { T t = pool.Dequeue(); return t; } return Activator.CreateInstance(); } public void Release(T t) { if (pool.Count < PoolSize) { if (t == null) { BFLog.LogError("try pool null item"); throw new ArgumentNullException(); } pool.Enqueue(t); } else { t = null; } } public void Clear() { pool.Clear(); } } public class GameObjectPool : IObjectPool { Dictionary> poolDict; Transform root; public GameObjectPool() { poolDict = new Dictionary>(); var go = new GameObject("globalPool"); UEObject.DontDestroyOnLoad(go); root = go.transform; } public GameObject Get(string resPath) { if (poolDict.TryGetValue(resPath, out List pool)) { var count = pool.Count; if (count > 0) { var index = count - 1; var result = pool[index]; pool.RemoveAt(index); return result; } } return null; } public void Release(GameObject gameObject, string resPath) { if (!poolDict.TryGetValue(resPath, out List pool)) { pool = new List(5); // 预分配 } gameObject.SetActive(false); gameObject.transform.parent = root; pool.Add(gameObject); } public void Clear() { } } }