using System.Collections.Generic; using UnityEngine; namespace AI { public class ProjectilePool : MonoBehaviour { private static ProjectilePool _instance = null; public static ProjectilePool Instance { get { if (_instance == null) { GameObject go = new GameObject(typeof(ProjectilePool).Name); _instance = go.AddComponent<ProjectilePool>(); } return _instance; } } public Stack<Projectile> pool = null; private GameObject prefab; private void Awake() { if (_instance != this && _instance != null) { Destroy(this); return; } pool = new Stack<Projectile>(64); prefab = Resources.Load<GameObject>("Projectiles/Basic Projectile"); } public Projectile Get() { Projectile projectile = null; pool.TryPop(out projectile); if (projectile == null) projectile = Instantiate(prefab).GetComponent<Projectile>(); projectile.gameObject.SetActive(true); return projectile; } public void Return(Projectile projectile) { projectile.gameObject.SetActive(false); pool.Push(projectile); } } }