94 lines
2.7 KiB
C#
94 lines
2.7 KiB
C#
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<T> where T : Component
|
|
{
|
|
[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;
|
|
public Action<T> OnGet { get; set; } = x=>x.gameObject.SetActive(true);
|
|
public Action<T> OnReturn { get; set; } = x=>x.gameObject.SetActive(false);
|
|
public Action<T> OnDestroy { get; set; } = x=>Object.Destroy(x.gameObject);
|
|
private ObjectPool<T> pool=> _pool ??=
|
|
new ObjectPool<T>
|
|
(Spawn, OnGet, OnReturn, OnDestroy,defaultCapacity:DefaultCapacity, maxSize:DefaultCapacity);
|
|
private ObjectPool<T> _pool;
|
|
private readonly List<T> _list=new();
|
|
|
|
public T Prefab
|
|
{
|
|
get => prefab;
|
|
set => prefab = value;
|
|
}
|
|
public Transform Root
|
|
{
|
|
get => root;
|
|
set => root = value;
|
|
}
|
|
|
|
public int DefaultCapacity
|
|
{
|
|
get => defaultCapacity;
|
|
set => defaultCapacity = value;
|
|
}
|
|
public int InstanceCount => _list.Count;
|
|
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);
|
|
#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
|
|
}
|
|
} |