Object Pool in C# Unity

public class PlayerBulletPool : MonoBehaviour
{
    List<GameObject> pooledObjects = new List<GameObject>();
    int amountToPool = 10;
    [SerializeField] GameObject bulletPrefab;

    void Start()
    {
        for (int i = 0; i < amountToPool; i++)
        {
            GameObject obj = Instantiate(bulletPrefab);
            obj.SetActive(false);
            pooledObjects.Add(obj);
        }
    }
    public GameObject GetPooledObject()
    {
        for (int i = 0; i < pooledObjects.Count; i++)
        {
            if (!pooledObjects[i].activeInHierarchy)
            {
                return pooledObjects[i];
            }
        }
        return null;
    }
}

PlayerBulletPool bulletPool;
    [SerializeField] int attack = 2;
    [SerializeField] float speed = 20f;

    private void Start() {
        bulletPool = GetComponent<PlayerBulletPool>();
    }
    private void Update() {
        if(Input.GetButtonDown("Fire1")){
            Shoot();
        }
    }
    void Shoot(){
        GameObject bullet = bulletPool.GetPooledObject();
        if(bullet){
            bullet.transform.position = new Vector3(transform.position.x + 1.5f, transform.position.y, 0);
            bullet.SetActive(true);
            bullet.GetComponent<Bullet>().Initialize(attack, speed);
        }
    }
public class Bullet : MonoBehaviour
{
    Rigidbody2D rb;
    int attack;
    float speed;

    public void Initialize(int attack, float speed){
        this.attack = attack;
        this.speed = speed;
    }
    private void OnEnable() {
        StartCoroutine(ReturnToPool(1f));
    }
    void Start(){
        rb = GetComponent<Rigidbody2D>();
    }
    void Update(){
        rb.velocity = new Vector2(speed,0f);
    }
    void OnCollisionEnter2D(Collision2D other) {
        if(other.gameObject.GetComponent<Hp>()){
            other.gameObject.GetComponent<Hp>().TakeDamage(attack);
        }
        StartCoroutine(ReturnToPool(0f));
    }

    IEnumerator ReturnToPool(float time){
        yield return new WaitForSeconds(time);
        gameObject.SetActive(false);
    }
}
Scroll to Top