使用方法
MyPool myPool;
myPool = new MyPool(bullet, 5);
GameObject g = myPool.Pop(firePos.position, Quaternion.identity);
g.GetComponent<Bullet>().onRecycleEvent += myPool.Push;
g.GetComponent<Bullet>().Init();
Bullet子弹代码
public interface IEnableRecycled
{
public event System.Action<GameObject> onRecycleEvent;
public void OnStartRecycle();
}
public class Bullet : MonoBehaviour,IEnableRecycled
{
public event Action< GameObject> onRecycleEvent;
public void Init() {
Invoke("IEnableRecycled.OnStartRecycle",2);
}
private void OnTriggerEnter2D(Collider2D other) {
Debug.Log(other.gameObject.layer.ToString()+","+layerMask.value);
if(1<<other.gameObject.layer==layerMask.value){
Debug.Log("撞击后回收");
OnStartRecycle();
}
}
void IEnableRecycled.OnStartRecycle()
{
if(onRecycleEvent!=null){
Debug.Log("开始回收资源");
onRecycleEvent(this.gameObject);
onRecycleEvent=null;
}
else{
Debug.Log("没有需要回收的资源");
}
}
}
资源池源代码
public class MyPool
{
public string poolName;
public Queue<GameObject> queue;
public Transform poolHolder;
public GameObject poolPrefab;
public MyPool(GameObject Prefab, int iniSize = 0, string Name = "", Transform Holder = null)
{
this.poolPrefab = Prefab;
this.poolHolder = Holder;
this.poolName = Name;
if (poolPrefab == null)
{
Debug.LogWarning("pool");
}
queue = new Queue<GameObject>();
if (poolHolder == null)
{
if(this.poolName.Equals("")) poolName = Random.Range(0, 101).ToString();
this.poolHolder = (new GameObject("Pool-" + this.poolName)).transform;
}
if (iniSize > 0)
{
for (int i = 0; i < iniSize; i++)
{
GameObject obj = GameObject.Instantiate(this.poolPrefab, this.poolHolder);
this.Push(obj);
}
}
}
public GameObject Pop()
{
if (queue.Count == 0)
{
GameObject obj = GameObject.Instantiate(poolPrefab, poolHolder);
return obj;
}
else
{
queue.Peek().SetActive(true);
return queue.Dequeue();
}
}
public GameObject Pop(Vector3 position, Quaternion rotation)
{
if (queue.Count == 0)
{
GameObject obj = GameObject.Instantiate(poolPrefab, position, rotation);
obj.transform.SetParent(poolHolder);
return obj;
}
else
{
GameObject obj = queue.Dequeue();
obj.SetActive(true);
obj.transform.SetPositionAndRotation(position, rotation);
return obj;
}
}
public void Push(GameObject item)
{
if (item == null)
{
Debug.LogWarning("push空对象");
return;
}
item.SetActive(false);
queue.Enqueue(item.gameObject);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!