提交
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace Roy.ObjectPool
|
||||
{
|
||||
|
||||
public class ObjectPool<T> where T : ObjectPoolItem
|
||||
{
|
||||
private readonly Queue<T> _pool; // 存储可重用对象的队列
|
||||
private readonly T _prefab; // 预制体
|
||||
private readonly string _poolName; // 预制体
|
||||
private readonly Transform _parent; // 对象的父级
|
||||
|
||||
// 构造函数
|
||||
public ObjectPool(string objectName, T prefab, int initialSize, Transform parent = null)
|
||||
{
|
||||
_poolName = objectName;
|
||||
_prefab = prefab;
|
||||
_parent = parent;
|
||||
_pool = new Queue<T>();
|
||||
|
||||
// 初始化对象池
|
||||
for (int i = 0; i < initialSize; i++)
|
||||
{
|
||||
T obj = CreateInstance();
|
||||
_pool.Enqueue(obj);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建对象的实例
|
||||
private T CreateInstance()
|
||||
{
|
||||
var gameObject = Object.Instantiate(_prefab.gameObject, _parent);
|
||||
gameObject.SetActive(false); // 初始化时设置为不激活
|
||||
var instance = gameObject.GetComponent<T>();
|
||||
instance.objectName = _poolName;
|
||||
return instance;
|
||||
}
|
||||
|
||||
// 获取一个对象
|
||||
public T Get()
|
||||
{
|
||||
if (_pool.Count > 0)
|
||||
{
|
||||
T obj = _pool.Dequeue();
|
||||
obj.gameObject.SetActive(true); // 获取时激活对象
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 如果没有可用对象,创建一个新的
|
||||
var obj = CreateInstance();
|
||||
obj.gameObject.SetActive(true);// 激活对象
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
// 归还对象
|
||||
public void ReturnToPool(T obj)
|
||||
{
|
||||
obj.OnRecycle();
|
||||
|
||||
obj.gameObject.SetActive(false); // 归还时设置为不激活
|
||||
obj.transform.SetParent(_parent);
|
||||
obj.transform.localPosition = Vector3.zero;
|
||||
|
||||
|
||||
_pool.Enqueue(obj); // 将对象返回池中
|
||||
}
|
||||
|
||||
// 清空对象池
|
||||
public void ClearPool()
|
||||
{
|
||||
while (_pool.Count > 0)
|
||||
{
|
||||
T obj = _pool.Dequeue();
|
||||
Object.Destroy(obj.gameObject); // 清除所有对象
|
||||
}
|
||||
|
||||
Object.Destroy(_parent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user