12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- 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);
- }
- }
- }
- }
|