This commit is contained in:
Gerard Gascón 2025-04-24 17:43:50 +02:00
commit 78b901484a
323 changed files with 109774 additions and 0 deletions

View file

@ -0,0 +1,3 @@
public interface IPooledObject{
void OnObjectSpawn();
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 29bcf1e7786d2d84882a1099b157f127
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,58 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour{
[System.Serializable]
public class Pool{
public string tag;
public GameObject prefab;
public int size;
}
[SerializeField] List<Pool> pools;
[SerializeField] Dictionary<string, Queue<GameObject>> poolDictionary;
public static ObjectPooler instance;
void Awake(){
instance = this;
poolDictionary = new Dictionary<string, Queue<GameObject>>();
foreach (Pool pool in pools){
Queue<GameObject> objectPool = new Queue<GameObject>();
for (int i = 0; i < pool.size; i++){
GameObject obj = Instantiate(pool.prefab, transform);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
poolDictionary.Add(pool.tag, objectPool);
}
}
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation){
if (!poolDictionary.ContainsKey(tag)){
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
if(pooledObj != null){
pooledObj.OnObjectSpawn();
}
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aed773e06e153e243972de36c1a5e75a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: