12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- namespace Pools
- {
- public class CoinPool : MonoBehaviour
- {
- public int initialSize = 50;
- public int amountIncrease = 5;
- public GameObject prefab;
- private HashSet<GameObject> active;
- private Queue<GameObject> inactive;
- 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.transform.SetPositionAndRotation(Vector3.zero, Quaternion.Euler(Vector3.zero));
- item.SetActive(true);
- active.Add(item);
- return item;
- }
- public void ReturnToPool(GameObject item)
- {
- if (active.Remove(item))
- {
- item.SetActive(false);
- inactive.Enqueue(item);
- }
- }
- }
- }
|