Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This work by Jason "Aj" Comfort (https://weirdbearddev.com) is licensed under
- * CC BY-SA 4.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-sa/4.0
- */
- using System.Collections.Generic;
- using UnityEngine;
- namespace SpaceMonkeys.Core
- {
- public class QueuePool : MonoBehaviour
- {
- #region Members
- [SerializeField] private GameObject _prefab = default;
- [SerializeField] private Queue<GameObject> _pool = default;
- [SerializeField] private int _poolSize = 10;
- private const int _increaseWhenEmpty = 10;
- #endregion Members
- #region MonoBehaviours
- void Awake() => GeneratePool();
- #endregion MonoBehaviours
- #region Methods
- /// <summary>
- /// Gets the first item from the queue. The position and rotation are equal to QueuePool's, and it is active.
- /// </summary>
- /// <returns>The GameObject from the QueuePool.</returns>
- public GameObject Request()
- {
- if (_pool.Count > 0)
- {
- GameObject item = _pool.Dequeue();
- item.transform.SetPositionAndRotation(transform.position, transform.rotation);
- item.SetActive(true);
- return item;
- }
- else
- {
- IncreasePool(_increaseWhenEmpty);
- return Request();
- }
- }
- public void Return(GameObject item)
- {
- item.SetActive(false);
- item.transform.SetPositionAndRotation(transform.position, transform.rotation);
- if (!_pool.Contains(item))
- _pool.Enqueue(item);
- }
- #endregion Methods
- #region Helpers
- private void GeneratePool()
- {
- _pool = new Queue<GameObject>(_poolSize);
- AddItems(_poolSize);
- }
- private void IncreasePool(int amount)
- {
- _poolSize += amount;
- AddItems(amount);
- }
- private void AddItems(int amount)
- {
- for (int i = 0; i < amount; i++)
- {
- GameObject p = Instantiate(_prefab, transform);
- p.name = $"{p.name}-{i}";
- p.SetActive(false);
- if (!_pool.Contains(p))
- _pool.Enqueue(p);
- }
- }
- #endregion Helpers
- }
- }
Add Comment
Please, Sign In to add comment