unity/유니티 초보

Unity - prefab을 이용한 간단한 ObjectPool

rimugiri 2024. 5. 30. 03:22
728x90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// prefab의 고유 HashCode를 key로 사용하여 prefab관리
/// Get("Your Prefab") 함수를 통해 사용 가능한 오브젝트를 반환
/// </summary>
public class ObjectPoolTest : MonoBehaviour
{
    [SerializeField] GameObject _prefab;

    private Dictionary<int, List<GameObject>> _pool = new Dictionary<int, List<GameObject>>();

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject go = Get(_prefab);
            go.transform.position = new Vector3(Random.Range(-5f, 5f), 0, Random.Range(-5f, 5f));
            StartCoroutine(Return(go));
        }
    }

    public void Init(GameObject prefab)
    {
        int key = prefab.GetHashCode();
        _pool.Add(key, new List<GameObject>());

        for (int i = 0; i < 10; i++)
        {
            CreateObject(prefab);
        }
    }
    public GameObject CreateObject(GameObject prefab)
    {
        int key = prefab.GetHashCode();
        GameObject go = Instantiate(_prefab);

        go.SetActive(false);
        _pool[key].Add(go);

        return go;
    }
    public GameObject Get(GameObject prefab)
    {
        GameObject go = null;
        int key = prefab.GetHashCode();

        if (_pool.ContainsKey(key) == false)
        {
            Init(prefab);
        }

        List<GameObject> pool = _pool[key];

        for (int i = 0; i < pool.Count; i++)
        {
            if (!pool[i].activeInHierarchy)
            {
                go = pool[i];
                go.SetActive(true);
                return go;
            }
        }

        go = CreateObject(prefab);
        go.SetActive(true);

        return go;
    }
    IEnumerator Return(GameObject go)
    {
        yield return new WaitForSeconds(10f);
        go.SetActive(false);
    }
}
728x90