Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.90 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace GuildUp
  6. {
  7. public class PoolManager : MonoBehaviour
  8. {
  9. public List<GameObject> PooledPrefab = new List<GameObject>();
  10. public List<int> NbPooledPrefab = new List<int>();
  11. public Dictionary<string,List<GameObject>> Pool = new Dictionary<string, List<GameObject>>();
  12.  
  13. private List<string> NamePooledPrefab = new List<string>();
  14.  
  15. private static PoolManager instance = null;
  16.  
  17. public static PoolManager Instance
  18. {
  19. get
  20. {
  21. return instance;
  22. }
  23. }
  24.  
  25. private void Awake()
  26. {
  27. instance = this;
  28. }
  29.  
  30. // Use this for initialization
  31. void Start()
  32. {
  33. initPool();
  34. }
  35.  
  36. private void initPool()
  37. {
  38. NamePooledPrefab = new List<string>();
  39. Pool = new Dictionary<string, List<GameObject>>();
  40.  
  41. for (int i = 0; i < PooledPrefab.Count; i++)
  42. {
  43. NamePooledPrefab.Add(PooledPrefab[i].name);
  44. for (int j = 0; j < NbPooledPrefab[i]; j++)
  45. SetToPool(Instantiate(PooledPrefab[i]));
  46. }
  47. }
  48.  
  49. public GameObject GetFromPool(GameObject prefab, Transform parent=null)
  50. {
  51. Debug.Log("Getted from pool");
  52. if (!Pool.ContainsKey(prefab.name))
  53. {
  54. Debug.LogError("Prefab not referenced in the pool : " + prefab.name);
  55. return InstantiatePooledObject(prefab,parent);
  56. }
  57. else if(Pool[prefab.name].Count == 0)
  58. {
  59. Debug.LogError("Instance generated out of the pool : " + prefab.name);
  60. return InstantiatePooledObject(prefab, parent);
  61. }
  62. GameObject lPooledObject = Pool[prefab.name][0];
  63. lPooledObject.SetActive(true);
  64. lPooledObject.transform.SetParent(parent);
  65. Pool[prefab.name].RemoveAt(0);
  66. return lPooledObject;
  67. }
  68.  
  69. private GameObject InstantiatePooledObject(GameObject prefab, Transform parent)
  70. {
  71. GameObject lPooledObject;
  72. lPooledObject = Instantiate(prefab, parent);
  73. lPooledObject.name = prefab.name;
  74. return lPooledObject;
  75. }
  76.  
  77. public void SetToPool(GameObject poolObject)
  78. {
  79. poolObject.SetActive(false);
  80. poolObject.transform.SetParent(transform);
  81. if (Pool.ContainsKey(poolObject.name))
  82. Pool[poolObject.name].Add(poolObject);
  83. else
  84. {
  85. Debug.Log("New Pool Key : " + poolObject.name);
  86. Pool.Add(poolObject.name, new List<GameObject> { poolObject });
  87. }
  88. }
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement