unity object pooling

Unity3D 2023. 2. 5. 21:03
반응형

 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    public static ObjectPool instance;
    public GameObject prefab;

    private Queue<GameObject> queue = new Queue<GameObject>();
    private void Awake()
    {
        ObjectPool.instance = this;
    }

    public void Load()
    {
        for (int i = 0; i < 10; i++)
        {
            var go = Instantiate(this.prefab, this.transform);
            go.SetActive(false);
            queue.Enqueue(go);
            
        }
    }

    public GameObject GetBullet()
    {
        if (queue.TryDequeue(out GameObject bulletGo))
        {
            bulletGo.transform.SetParent(null);
            bulletGo.SetActive(true);
            return bulletGo;
        }
        else
        {
            return Instantiate(this.prefab);
        }
    }

    public void ReleaseBullet(GameObject bulletGo)
    {
        queue.Enqueue(bulletGo);
        bulletGo.transform.SetParent(this.transform);
        bulletGo.transform.localPosition = Vector3.zero;
        bulletGo.SetActive(false);
    }
}
반응형
: