Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- public class CustomObjectPooling : MonoBehaviour {
- [System.Serializable]
- public class ObjPool
- {
- public string objKey;
- public GameObject objPrefab;
- public int size;
- }
- GameManager gameInstance;
- public static CustomObjectPooling instance;
- public List<ObjPool> objPools;
- public Dictionary<string, Queue<GameObject>> objectPoolDictionary;
- private void Awake()
- {
- if(instance != null)
- {
- Debug.Log("already have objectpool");
- return;
- }
- instance = this;
- }
- // Use this for initialization
- void Start () {
- gameInstance = GameManager.gameInstance;
- objectPoolDictionary = new Dictionary<string, Queue<GameObject>>();
- foreach(ObjPool objPool in objPools)
- {
- Queue<GameObject> objectPool = new Queue<GameObject>();
- for(int i = 0; i < objPool.size; i++)
- {
- GameObject obj = Instantiate(objPool.objPrefab);
- obj.SetActive(false);
- objectPool.Enqueue(obj);
- }
- objectPoolDictionary.Add(objPool.objKey, objectPool);
- }
- }
- public GameObject SpawnObjFromPool(string _objKey, Vector3 position, Quaternion rotation)
- {
- if (!objectPoolDictionary.ContainsKey(_objKey))
- {
- Debug.LogWarning("Pool with key" + _objKey + "doesn't exist");
- return null;
- }
- GameObject objectSpawned = objectPoolDictionary[_objKey].Dequeue();
- objectSpawned.SetActive(true);
- objectSpawned.transform.position = position;
- objectSpawned.transform.rotation = rotation;
- IPooledObject pooledObject = objectSpawned.GetComponent<IPooledObject>();
- if(pooledObject != null)
- {
- pooledObject.SpawnEnemy();
- gameInstance.enemiesAlive++;
- }
- objectPoolDictionary[_objKey].Enqueue(objectSpawned);
- return objectSpawned;
- }
- }
- WaveSpawner.cs
- ......
- IEnumerator SpawnWaveFirstLocation()
- {
- GameObject objSpawned;
- Wave wave = waves[waveNumber];
- for(int i = 0; i < wave.count; i++)
- {
- enemiesAlive++;
- objSpawned = objectPooler.SpawnObjFromPool(wave.enemyNameKey, transform.position, Quaternion.identity);
- yield return new WaitForSeconds(1f / wave.rate);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement