Advertisement
diliupg

PoolManager

Apr 13th, 2021
1,022
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. /*
  2. ==========================
  3. Copyright (c) Diliupg 2020
  4.    www.soft.diliupg.com
  5. ==========================
  6. */
  7.  
  8. using UnityEngine;
  9. using System.Collections.Generic;
  10.  
  11. public class PoolManager : MonoBehaviour
  12. {
  13.     //float scaleAmount = 1f;
  14.  
  15.     [System.Serializable]
  16.     public class Pool
  17.     {
  18.         public int tag;
  19.         public GameObject prefab;
  20.         public int size;
  21.     }
  22.  
  23.     public List<Pool> Pools;
  24.     private Pool pool;
  25.     public Dictionary<int, Queue<GameObject>> PoolDictionary;
  26.  
  27.     void Start ( )
  28.     {
  29.         Init ( );
  30.     }
  31.  
  32.     void Init ( )
  33.     {
  34.         PoolDictionary = new Dictionary<int, Queue<GameObject>> ( );
  35.  
  36.         foreach ( Pool pool in Pools )
  37.         {
  38.             Queue<GameObject> objectPool = new Queue<GameObject> ( );
  39.  
  40.             for ( int i = 0 ; i < pool.size ; i++ )
  41.             {
  42.                 GameObject obj = Instantiate ( pool.prefab );
  43.  
  44.                 obj.SetActive ( false );
  45.                 objectPool.Enqueue ( obj ); // add to the queue
  46.             }
  47.  
  48.             PoolDictionary.Add ( pool.tag, objectPool );
  49.         }
  50.     }
  51.  
  52.     public GameObject SpawnFromPool ( int tag, Vector2 position )
  53.     {
  54.         if ( !PoolDictionary.ContainsKey ( tag ) )
  55.         {
  56.             //Debug.LogWarning ( "Pool with tag " + tag + "doesn't exist" );
  57.             return null;
  58.         }
  59.  
  60.         GameObject objectToSpawn = PoolDictionary [ tag ].Dequeue ( ); // remove from the queue
  61.  
  62.         objectToSpawn.SetActive ( true );
  63.         objectToSpawn.transform.position = position;
  64.  
  65.         PoolDictionary [ tag ].Enqueue ( objectToSpawn ); // put back in the queue
  66.  
  67.         return objectToSpawn;
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement