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);
}
}
반응형
'Unity3D' 카테고리의 다른 글
ASTC 와 ETC2 (0) | 2023.07.04 |
---|---|
종스크롤 2D 슈팅게임 배경 스크롤링 (0) | 2023.02.05 |
온디맨드 렌더링을 이용한 모바일 성능 개선 (0) | 2022.11.28 |
유니티 스크립트 Missing 한번에 지우기 (SelectGameObjectsWithMissingScripts) (0) | 2022.05.10 |
Load font from mobile device and assign as fallback TMP_FontAsset (0) | 2022.05.03 |