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
'unity > 유니티 초보' 카테고리의 다른 글
Unity2D 절차 지향적 맵 생성 (0) | 2024.08.18 |
---|---|
Unity - firebase realtimeDatabase, auth를 이용한 채팅 구현해보기 (0) | 2024.08.15 |
Unity 카메라 기능들 정리 (0) | 2024.05.28 |
Unity - 부드러운 카메라 회전 (0) | 2024.05.27 |
Unity - Lerp 다양한 사용법 (0) | 2024.05.27 |