generated from pancake-llc/package
-
Notifications
You must be signed in to change notification settings - Fork 16
Pool
Aprius edited this page Aug 28, 2024
·
16 revisions
You can get object from pool via extension method Request
using Pancake;
[SerializeField] private GameObject prefab;
prefab.Request();
//request with set position
prefab.Request(Vector3.zero);
//request with return component
prefab.Request<Type Component>();
You can return object to pool via extension method Return
using Pancake;
[SerializeField] private GameObject prefab;
var instance = prefab.Request();
instance.Return(); // return instance into pool
You can prewarm pool with Prewarm
method
using Pancake.Pools;
using UnityEngine;
public sealed class AudioManager : MonoBehaviour
{
[SerializeField] private GameObject prefab;
[SerializeField] private int prewarmSize = 10;
private void Awake()
{
prefab.Prewarm(prewarmSize);
}
}
When using the pool, we have two callbacks: callback when an object is removed from the pool and callback when an object is returned to the pool.
-
OnRequest
: callback when an object is take out the pool -
OnReturn
: callback when an object is put back the pool
To implement these two callbacks we need to implement the IPoolCallbackReceiver
interface
using Pancake.Pools;
using UnityEngine;
public class Enemy: MonoBehaviour, IPoolCallbackReceiver
{
[SerializeField] private float maxHP = 100f;
private float _currentHP = 0f;
/// <summary>
/// This method will be called before Awake
/// </summary>
public void OnRequest()
{
_currentHP = maxHP;
}
public void OnReturn()
{
// TO_DO
}
}
using Pancake.Pools;
public class PooledObject
{
}
public sealed class CustomObjectPool : ObjectPoolBase<PooledObject>
{
protected override PooledObject CreateInstance() { return new PooledObject(); }
protected override void OnDestroy(PooledObject instance)
{
// Add actions when the object is destroyed in Clear or Dispose
}
protected override void OnRequest(PooledObject instance)
{
// Add actions when requested
}
protected override void OnReturn(PooledObject instance)
{
// Add actions when returned
}
}
private void Start()
{
var pool = new CustomObjectPool();
var pooledObject = pool.Request();
}