과거에는 유니티에서 자체적으로 오브젝트 풀링을 지원하지 않아서 사람마다 구현 방법과 성능이 달랐지만
이제는 유니티에서 공식적으로 지원하는 기능을 사용 할 수 있다
일딴 핵심은 using에
using using UnityEngine.Pool;
그리고
1. 생성 = Instantiate()
2. 사용 = SetActive(true)
3. 반환 = SetActive(false)
4. 삭제 = Destroy()
이 4개를 Awake()시에 선언해서 Pool에 함수로 넣어서 나중에 수정 시 확장성 있게 추가가 가능하다
MyObjectPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class MyObjectPool : MonoBehaviour
{
//오브젝트 자체에서 어떤 Pool에 들어가야 하는지 알고 있어야함.
public IObjectPool<MyGameObject> m_gameObjectPool;
public MyGameObject m_gameObjectBase;
void Awake()
{
m_gameObjectPool = new ObjectPool<MyGameObject>(
CreateGameObjectBase,
OnGet,
OnRelease,
OnDestory,
maxSize : 5
);
}
private MyGameObject CreateGameObjectBase(){
MyGameObject gameObjectBase = Instantiate(m_gameObjectBase).GetComponent<MyGameObject>();
gameObjectBase.transform.SetParent(this.transform);
gameObjectBase.m_gameObjectPool = this;
return gameObjectBase;
}
//=> Get이 실행될 때 실행되는 함수 => element가 parameter가 됨
private void OnGet(MyGameObject _gameObjectBase)
{
_gameObjectBase.gameObject.SetActive(true);
_gameObjectBase.transform.position = Vector3.zero;
}
//=> Release가 실행될 때 실행되는 함수 element가 실행함.
private void OnRelease(MyGameObject _gameObjectBase)
{
_gameObjectBase.gameObject.SetActive(false);
}
private void OnDestory(MyGameObject _gameObjectBase)
{
Destroy(_gameObjectBase.gameObject);
}
public void OnClickGetGameObject(){
m_gameObjectPool.Get();
// MyGameObject gameObjectBase = m_gameObjectPool.Get();
}
}
MyGameObject.cs
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Pool;
public class MyGameObject : MonoBehaviour
{
public MyObjectPool m_gameObjectPool;
public float m_speed = 5f;
void Update(){
// 날라가면 삭제 해주기
if (this.transform.position.y > 5)
{
m_gameObjectPool.m_gameObjectPool.Release(this);
// Destroy(this.gameObject);
}
this.transform.Translate(Vector3.up * this.m_speed * Time.deltaTime);
}
}
이렇게 물체를 날라가는 것을 쉽게 구현 할 수 있었다
하이라이키 창을 보면 초기 5개 설정 한 것에서 벗어나지 않고 5개 이후로는 Destrory되고 나머지는 Release()되는 것을 볼 수 있다
'Unity' 카테고리의 다른 글
NewInputSystem (1) | 2024.01.14 |
---|---|
유니티 사운드 매니저 (0) | 2023.12.10 |
AOSFogWar (0) | 2023.12.03 |
Dotween 맛보기 (0) | 2023.12.03 |
UGS 맛보기 (0) | 2023.11.20 |