Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- namespace GuildUp
- {
- public class PoolManager : MonoBehaviour
- {
- public List<GameObject> PooledPrefab = new List<GameObject>();
- public List<int> NbPooledPrefab = new List<int>();
- public Dictionary<string,List<GameObject>> Pool = new Dictionary<string, List<GameObject>>();
- private List<string> NamePooledPrefab = new List<string>();
- private static PoolManager instance = null;
- public static PoolManager Instance
- {
- get
- {
- return instance;
- }
- }
- private void Awake()
- {
- instance = this;
- }
- // Use this for initialization
- void Start()
- {
- initPool();
- }
- private void initPool()
- {
- NamePooledPrefab = new List<string>();
- Pool = new Dictionary<string, List<GameObject>>();
- for (int i = 0; i < PooledPrefab.Count; i++)
- {
- NamePooledPrefab.Add(PooledPrefab[i].name);
- for (int j = 0; j < NbPooledPrefab[i]; j++)
- SetToPool(Instantiate(PooledPrefab[i]));
- }
- }
- public GameObject GetFromPool(GameObject prefab, Transform parent=null)
- {
- Debug.Log("Getted from pool");
- if (!Pool.ContainsKey(prefab.name))
- {
- Debug.LogError("Prefab not referenced in the pool : " + prefab.name);
- return InstantiatePooledObject(prefab,parent);
- }
- else if(Pool[prefab.name].Count == 0)
- {
- Debug.LogError("Instance generated out of the pool : " + prefab.name);
- return InstantiatePooledObject(prefab, parent);
- }
- GameObject lPooledObject = Pool[prefab.name][0];
- lPooledObject.SetActive(true);
- lPooledObject.transform.SetParent(parent);
- Pool[prefab.name].RemoveAt(0);
- return lPooledObject;
- }
- private GameObject InstantiatePooledObject(GameObject prefab, Transform parent)
- {
- GameObject lPooledObject;
- lPooledObject = Instantiate(prefab, parent);
- lPooledObject.name = prefab.name;
- return lPooledObject;
- }
- public void SetToPool(GameObject poolObject)
- {
- poolObject.SetActive(false);
- poolObject.transform.SetParent(transform);
- if (Pool.ContainsKey(poolObject.name))
- Pool[poolObject.name].Add(poolObject);
- else
- {
- Debug.Log("New Pool Key : " + poolObject.name);
- Pool.Add(poolObject.name, new List<GameObject> { poolObject });
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement