Object Pooling in Unity - Unity By Example

Object Pooling in Unity

Merging objects is a way to simplify your designs and reduce CPU usage when you need to quickly create and destroy new objects.

Steps

  • Create script ObjectPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    [SerializeField] private Enemy _enemy;
    private List<Enemy> _enemies = new();

    private void Start()
    {
        StartCoroutine(Instantiate());
    }

    private IEnumerator Instantiate()
    {
        int enemyCount = 5;
        while (true)
        {
            for(int i = 0; i < enemyCount; i++)
            {
                Enemy enemyPool = GetPooledObject();
                if(enemyPool is null)
                {
                    Enemy enemy = Instantiate(_enemy, new Vector3(Random.Range(0f, 10f), 0, Random.Range(0f, 10f)), Quaternion.identity);
                    _enemies.Add(enemy);
                    enemy.Initialize($"Enemy {_enemies.Count}");
                }
                else
                {
                    enemyPool.Revival();
                    enemyPool.ChangeName($"Enemy pooled");
                }
            }

            yield return new WaitForSeconds(2f);

            foreach(Enemy enemy in _enemies)
            {
                enemy.Death();
            }

            enemyCount += 5;
        }
    }

    private Enemy GetPooledObject()
    {
        for (int i = 0; i < _enemies.Count; i++)
        {
            if (!_enemies[i].gameObject.activeSelf)
            {
                return _enemies[i];
            }
        }

        return null;
    }
}

  • Create script Enemy.cs
using TMPro;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    [SerializeField] private TMP_Text _name;
    
    public void Initialize(string name)
    {
        _name.text = name;  
    }

    public void ChangeName(string name)
    {
        _name.text = name;
        _name.color = Color.green;
    }

    public void Revival()
    {
        gameObject.SetActive(true);
    }

    public void Death()
    {   
        gameObject.SetActive(false);
    }
}

  • Add an object to the scene that will be an enemy.
  • Create empty object and attach script ObjectPool.cs

Result

Download

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments