123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- using Object = UnityEngine.Object;
- namespace Pools
- {
- public class Pool : MonoBehaviour
- {
- public int initialSize = 10;
- public int amountIncrease = 5;
- public GameObject prefab;
- private Queue<GameObject> inactive;
- private HashSet<GameObject> active;
- private void Awake()
- {
- active = new HashSet<GameObject>();
- inactive = new Queue<GameObject>();
- IncreasePool(initialSize);
- }
- private void IncreasePool(int amount)
- {
- for (var i = 0; i < amount; i++)
- {
- var item = Instantiate(prefab, transform);
- item.SetActive(false);
- inactive.Enqueue(item);
- }
- }
- public GameObject GetItem()
- {
- GameObject item;
- if (inactive.Count > 0)
- {
- item = inactive.Dequeue();
- }
- else
- {
- IncreasePool(amountIncrease);
- item = inactive.Dequeue();
- }
- item.SetActive(true);
- active.Add(item);
- return item;
- }
- public void ReturnToPool(GameObject item)
- {
- if (active.Remove(item))
- {
- item.SetActive(false);
- inactive.Enqueue(item);
- }
- }
- }
- }
|