BITKit/Packages/Runtime~/Unity/Scripts/Utility/Pool.cs

56 lines
1.6 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
{
public UnityPool()
{
pool = new ObjectPool<T>(Spawn, OnGet, OnReturn, OnDestroy, maxSize: 16);
}
[Header(Constant.Header.Prefabs)]
public T prefab;
[Header(Constant.Header.Gameobjects)]
public Transform root;
private ObjectPool<T> 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<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
}
}