Skip to content
Aprius edited this page Aug 28, 2024 · 16 revisions

Usages

How get object from pool

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>();

How return object to pool

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

Prewarm 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);
    }
}

Use callbacks

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
	}
}

Generic Pool

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();
}
Clone this wiki locally