using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Xml.Linq; using UnityEngine; using UnityEngine.Pool; using Object = UnityEngine.Object; namespace BITKit { [System.Serializable] public class UnityPool where T : Component { public UnityPool() { pool = new ObjectPool(Spawn, OnGet, OnReturn, OnDestroy, maxSize: 16); } [Header(Constant.Header.Settings)] [SerializeField] private int defaultCapacity = 16; [Header(Constant.Header.Prefabs)] [SerializeField] private T prefab; [Header(Constant.Header.Gameobjects)] [SerializeField] private Transform root; private ObjectPool pool; private readonly List _list=new(); public int DefaultCapacity { get => defaultCapacity; set => defaultCapacity = value; } public T Get(T element = null, Transform _root = null) { if (_list.Count == defaultCapacity) { var next = _list[0]; next.gameObject.SetActive(false); _list.RemoveAt(0); _list.Add(next); next.gameObject.SetActive(true); return next; } if (element is not null) prefab = element; if (_root is not null) root = _root; var instance = pool.Get(); _list.Add(instance); return instance; } public void Return(T element) { pool.Release(element); _list.Remove(element); } private T Spawn() => Object.Instantiate(prefab, root); private void OnGet(T element) => element.gameObject.SetActive(true); private void OnReturn(T element) => element.gameObject.SetActive(false); private void OnDestroy(T element) => Object.Destroy(element.gameObject); #region 拓展 private readonly ConcurrentDictionary _dictionary=new(); public T GetByKey(string key) { var instance = _dictionary.GetOrAdd(key, s => Get()); return instance; } public void RemoveByKey(string key) { _dictionary.TryRemove(key); } #endregion } }