generic pool made

This commit is contained in:
Mausham
2025-12-17 15:50:28 -08:00
parent ff062d4c3d
commit 2a7759228f
29 changed files with 265 additions and 227 deletions

View File

@@ -0,0 +1,60 @@
using Darkmatter.Core;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
using VContainer;
using VContainer.Unity;
namespace Darkmatter.Presentation
{
public class ObjectPool<T> : MonoBehaviour,IPool<T> where T : MonoBehaviour, IPoolable
{
[SerializeField] T prefab;
[SerializeField] private Transform prefabParent;
[SerializeField] private int poolSize = 15;
public Queue<T> pool = new Queue<T>();
[Inject] IObjectResolver resolver;
public IReadOnlyCollection<T> All => pool;
private void Awake()
{
CreateObjectPool();
}
private void CreateObjectPool()
{
for(int i=0;i<poolSize; i++)
{
T obj = Instantiate(prefab, prefabParent);
resolver.InjectGameObject(obj.gameObject);
obj.OnSpawn();
obj.gameObject.SetActive(false);
pool.Enqueue(obj);
}
}
public T GetFromPool()
{
if(pool.Count == 0)
{
T obj = Instantiate(prefab, prefabParent);
resolver.InjectGameObject(obj.gameObject);
obj.OnSpawn();
obj.gameObject.SetActive(true);
pool.Enqueue(obj);
return obj;
}
T returningObj = pool.Dequeue();
return returningObj;
}
public void ReturnToPool(T obj)
{
obj.OnDespawn();
obj.gameObject.SetActive(false);
pool.Enqueue(obj);
}
}
}