Create ObjectPoolService

This commit is contained in:
2025-12-13 19:57:48 +08:00
parent 8915a26407
commit 980b26dd5e
5 changed files with 60 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
using System.Collections;
using System.Collections.Generic;
using Services.Interfaces;
using UnityEngine;
namespace Services {
public class ObjectPoolService:IObjectPool<GameObject> {
private readonly GameObject prefab;
private readonly Transform parent;
private readonly int size;
private readonly Stack<GameObject> pool = new Stack<GameObject>();
public ObjectPoolService(GameObject prefab, Transform parent, int size = 5) {
this.prefab = prefab;
this.parent = parent;
this.size = size;
}
public GameObject Get() {
return this.pool.Count == 0 ? Object.Instantiate(this.prefab, this.parent) : this.pool.Pop();
}
public void Fill() {
for (int i = 0; i < this.size; i++) {
Object.Instantiate(this.prefab, this.parent);
}
}
public void Release(GameObject gameObject) {
this.pool.Push(gameObject);
}
public void Clear() {
this.pool.Clear();
}
}
}