115 lines
2.7 KiB
C#
115 lines
2.7 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using UEObject = UnityEngine.Object;
|
|
|
|
namespace BF
|
|
{
|
|
public interface IObjectPool
|
|
{
|
|
void Clear();
|
|
}
|
|
|
|
public class ClassPool<T> : IObjectPool where T : class
|
|
{
|
|
static ClassPool<T> instance;
|
|
public static ClassPool<T> Create(int size = 100)
|
|
{
|
|
if (instance == null)
|
|
instance = new ClassPool<T>(size);
|
|
return instance;
|
|
}
|
|
|
|
private ClassPool(int poolSize = 100)
|
|
{
|
|
PoolSize = poolSize;
|
|
}
|
|
|
|
Queue<T> pool = new Queue<T>();
|
|
public int PoolSize { get; private set; }
|
|
|
|
public void SetPoolSize(int poolSize)
|
|
{
|
|
PoolSize = poolSize;
|
|
}
|
|
|
|
public T Get()
|
|
{
|
|
if (pool.Count > 0)
|
|
{
|
|
T t = pool.Dequeue();
|
|
return t;
|
|
}
|
|
return Activator.CreateInstance<T>();
|
|
}
|
|
|
|
public void Release(T t)
|
|
{
|
|
if (pool.Count < PoolSize)
|
|
{
|
|
if (t == null)
|
|
{
|
|
BFLog.LogError("try pool null item");
|
|
throw new ArgumentNullException();
|
|
}
|
|
pool.Enqueue(t);
|
|
}
|
|
else
|
|
{
|
|
t = null;
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
pool.Clear();
|
|
}
|
|
}
|
|
|
|
public class GameObjectPool : IObjectPool
|
|
{
|
|
Dictionary<string, List<GameObject>> poolDict;
|
|
Transform root;
|
|
|
|
public GameObjectPool()
|
|
{
|
|
poolDict = new Dictionary<string, List<GameObject>>();
|
|
var go = new GameObject("globalPool");
|
|
UEObject.DontDestroyOnLoad(go);
|
|
root = go.transform;
|
|
}
|
|
|
|
public GameObject Get(string resPath)
|
|
{
|
|
if (poolDict.TryGetValue(resPath, out List<GameObject> pool))
|
|
{
|
|
var count = pool.Count;
|
|
if (count > 0)
|
|
{
|
|
var index = count - 1;
|
|
var result = pool[index];
|
|
pool.RemoveAt(index);
|
|
return result;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public void Release(GameObject gameObject, string resPath)
|
|
{
|
|
if (!poolDict.TryGetValue(resPath, out List<GameObject> pool))
|
|
{
|
|
pool = new List<GameObject>(5); // 预分配
|
|
}
|
|
gameObject.SetActive(false);
|
|
gameObject.transform.parent = root;
|
|
pool.Add(gameObject);
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|