Skip to content

Object Pooling

DucNV_2000 edited this page Jun 14, 2024 · 7 revisions

Use

Note: From version 2.7.7 remove scriptable pool.

Demo use from version 2.7.7

    public GameObject objPrefab;
    public List<PoolData> listPreSpawn;
    private GameObject ins;

    /// <summary>
    /// Init Pool before use
    /// </summary>
    public void InitPool()
    {
        Pool.InitPool();
    }

    /// <summary>
    /// Pre Spawn game object
    /// </summary>
    private void PreSpawn()
    {
        foreach (var poolData in listPreSpawn)
        {
            poolData.PreSpawn();
        }
    }

    /// <summary>
    /// Spawn game object
    /// </summary>
    public void SpawnObj()
    {
        ins = Pool.Spawn(objPrefab);
        // or
        ins = objPrefab.Spawn();
    }

    /// <summary>
    /// DeSpawn game Object
    /// </summary>
    public void DeSpawnObj()
    {
        Pool.DeSpawn(ins);
        // or
        ins.DeSpawn();
    }

    /// <summary>
    /// DeSpawn all pool
    /// </summary>
    public void DeSpawnAll()
    {
        Pool.DeSpawnAll();
    }

    /// <summary>
    /// Destroy all game object pool
    /// </summary>
    public void DestroyAll()
    {
        Pool.DestroyAll();
    }

Previous versions used the same as below

Create ScriptableObject Pools (Open tab Pools Sunflower Control Panel)

Pools

After create Pools, declare Pool in class and drag ScriptableObject Pools from asset to inspector to use.

Screenshot 2023-10-10 at 23 25 31

Demo

using UnityEngine;
using VirtueSky.ObjectPooling;

public class TestPools : MonoBehaviour
{
    public Pools pools;
    public GameObject coinPrefab;

    private void Start()
    {
        pools.Initialize();
    }

    public void SpawnCoin()
    {
        pools.Spawn(coinPrefab);
    }

    public void DeSpawnCoinPrefab()
    {
        pools.Despawn(coinPrefab);
    }
}

Or you can customize GameObject Pool according to the example below

using UnityEngine;
using VirtueSky.ObjectPooling;

[CreateAssetMenu(menuName = "GameObjectPool/CurrencyPool", fileName = "currency_pool")]
public class CurrencyPool : GameObjectPool
{
}
  • Create ScriptableObject CurrencyPool

Screenshot 2024-02-22 171512

  • You need to drag the prefab into the GameObject Pool
  • Use GameObject Pool
public class Test : MonoBehaviour
{
    public CurrencyPool currencyPool;
    public Transform parent;
    private GameObject coin;

    private void Start()
    {
        currencyPool.PreSpawn();
    }

    void Spawn()
    {
        coin = currencyPool.Spawn(transform);
    }

    void DeSpawn()
    {
        currencyPool.DeSpawn(coin);
    }
}