2023-06-05 19:57:17 +08:00
|
|
|
using System;
|
|
|
|
using System.Collections;
|
2023-08-11 23:57:37 +08:00
|
|
|
using System.Collections.Concurrent;
|
2023-06-05 19:57:17 +08:00
|
|
|
using System.Collections.Generic;
|
2023-08-11 23:57:37 +08:00
|
|
|
using System.Xml.Linq;
|
2023-06-05 19:57:17 +08:00
|
|
|
using UnityEngine;
|
|
|
|
using UnityEngine.Pool;
|
2023-08-11 23:57:37 +08:00
|
|
|
using Object = UnityEngine.Object;
|
|
|
|
|
2023-06-05 19:57:17 +08:00
|
|
|
namespace BITKit
|
|
|
|
{
|
|
|
|
[System.Serializable]
|
|
|
|
public class UnityPool<T> where T : Component
|
|
|
|
{
|
|
|
|
public UnityPool()
|
|
|
|
{
|
2023-08-11 23:57:37 +08:00
|
|
|
pool = new ObjectPool<T>(Spawn, OnGet, OnReturn, OnDestroy, maxSize: 16);
|
2023-06-05 19:57:17 +08:00
|
|
|
}
|
2023-08-11 23:57:37 +08:00
|
|
|
|
2023-06-05 19:57:17 +08:00
|
|
|
[Header(Constant.Header.Prefabs)]
|
|
|
|
public T prefab;
|
|
|
|
[Header(Constant.Header.Gameobjects)]
|
|
|
|
public Transform root;
|
2023-08-11 23:57:37 +08:00
|
|
|
private ObjectPool<T> pool;
|
|
|
|
|
|
|
|
public T Get(T element = null, Transform _root = null)
|
2023-06-05 19:57:17 +08:00
|
|
|
{
|
|
|
|
if (element is not null)
|
|
|
|
prefab = element;
|
2023-08-11 23:57:37 +08:00
|
|
|
if (_root is not null)
|
|
|
|
root = _root;
|
2023-06-05 19:57:17 +08:00
|
|
|
return pool.Get();
|
|
|
|
}
|
|
|
|
public void Return(T element) => pool.Release(element);
|
2023-08-11 23:57:37 +08:00
|
|
|
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<string, T> _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
|
2023-06-05 19:57:17 +08:00
|
|
|
}
|
|
|
|
}
|