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.Prefabs)] public T prefab; [Header(Constant.Header.Gameobjects)] public Transform root; private ObjectPool pool; public T Get(T element = null, Transform _root = null) { if (element is not null) prefab = element; if (_root is not null) root = _root; return pool.Get(); } public void Return(T element) => pool.Release(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 } }