代码
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
public abstract class Objectpool<T> : MonoBehaviour where T : Component
{
private Queue<T> pool = new Queue<T>();
[SerializeField] private T prefab;
[SerializeField] private int maxPoolCapacity = 100;
public static Objectpool<T> Instance;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
if (Instance != this) Destroy(gameObject);
}
}
public T Get()
{
if (pool.Count == 0)
{
Add(1);
}
T obj = pool.Dequeue();
obj.gameObject.SetActive(true);
ResetObject(obj);
return obj;
}
protected abstract void ResetObject(T obj);
public void ReturnToPool(T obj)
{
obj.gameObject.SetActive(false);
pool.Enqueue(obj);
}
public void Add(int num)
{
if (prefab == null)
{
Debug.LogError("Prefab is null. Cannot instantiate objects.");
return;
}
if(pool.Count() + num >= maxPoolCapacity)
{
Debug.LogError("pool will be full!");
return;
}
for (int i = 0; i < num; i++)
{
var temp = Instantiate(prefab);
temp.gameObject.SetActive(false);
pool.Enqueue(temp);
}
}
}