Advertisement
Guest User

ObjPooler

a guest
May 22nd, 2020
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3.  
  4. [System.Serializable]
  5. public class ObjectPoolItem
  6. {
  7. public GameObject objectToPool;
  8. public int amountToPool;
  9. public bool shouldExpand;
  10. }
  11.  
  12.  
  13. public class ObjectPooler : MonoBehaviour
  14. {
  15. public static ObjectPooler SharedInstance;
  16. List<GameObject> pooledObjects;
  17. public List<ObjectPoolItem> itemsToPool;
  18.  
  19. private void Awake()
  20. {
  21. SharedInstance = this;
  22. }
  23.  
  24.  
  25.  
  26. // Start is called before the first frame update
  27. void Start()
  28. {
  29. pooledObjects = new List<GameObject>();
  30. foreach (ObjectPoolItem item in itemsToPool)
  31. {
  32. for (int i = 0; i < item.amountToPool; i++)
  33. {
  34. GameObject obj = (GameObject)Instantiate(item.objectToPool);
  35. obj.SetActive(false);
  36. pooledObjects.Add(obj);
  37. }
  38. }
  39. }
  40.  
  41. public GameObject GetPooledObject(string tag)
  42. {
  43. for (int i = 0; i < pooledObjects.Count; i++)
  44. {
  45. if (!pooledObjects[i].activeInHierarchy && pooledObjects[i].tag == tag)
  46. {
  47. return pooledObjects[i];
  48. }
  49. }
  50. foreach (ObjectPoolItem item in itemsToPool)
  51. {
  52. if (item.objectToPool.tag == tag)
  53. {
  54. if (item.shouldExpand)
  55. {
  56. GameObject obj = (GameObject)Instantiate(item.objectToPool);
  57. obj.SetActive(false);
  58. pooledObjects.Add(obj);
  59. return obj;
  60. }
  61. }
  62. }
  63. return null;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement