layer-plusObject pool

Example: Creating and Using a Pooled Object

Assume you have an object MyObject and you want to create and reuse it using an object pool.

Create a Prefab

  1. Create a prefab in the project, for example: MyObjectPrefab

  2. Create a script MyObject.cs and attach it to MyObjectPrefab.

using System;
using UnityEngine;
using Zenject;

namespace KrolStudio
{
    public class MyObject : MonoBehaviour, IPoolReturnable<MyObject>
    {
        public event Action<MyObject> OnReturned;
        
        public void ReturnToPool()
        {
            returned = true;
            OnReturned?.Invoke(this);
        } 
    }
}

Using a Factory for Object Creation

Because objects may require Zenject dependency injection, instances must be created via a factory using InstantiatePrefab.

Factory Overview

You need to work with two components: IGameFactory interface, GameFactory implementation.

  1. Add a method signature for creating MyObject:

  1. Register the prefab and pool configuration data in GameplayAssetsConfig:

Assign the MyObjectPrefab reference in the configuration asset.

  1. Add the factory method implementation using Zenject’s IInstantiator:

Pooling Integration

MyObject implements the IPoolReturnable<MyObject> interface, allowing it to be reused via an object pool.

  • The OnReturned event notifies the pool manager when the myObject should be recycled.

  • The ReturnToPool() method ensures that the myObject is returned only once.

Connecting the Factory to the Pool

  1. The pool must know how to create objects of type MyObject. To achieve this, update the Create() method in the ObjectFactory class:

  1. In the GameplayBootstrapState class, where all pools are initialized, add initialization for the MyObject pool.

3. To obtain a MyObject instance from the pool:

After usage, the object is automatically returned to the pool by calling:

Last updated