CodeBlanks Logo Icon CodeBlanks

Object pooling revisited

Deepen object pooling use for memory.

What is object pooling?

Object pooling is the technique of keeping objects in a pool and reusing them instead of destroying them. When an object in the pool finishes its job it is not destroyed; it is deactivated and later used again. This way constant allocation and collection cost drops.

gameObject.SetActive(false); // deactivate instead of destroy
nesne = havuzdakiNesne;      // reuse

A pool is ideal for objects created frequently.

How does a pool work?

A pool keeps prepared objects in a list. When needed an object is taken from the list, and when the job is done it is given back. Using an old object instead of producing a new one is far more efficient for memory.

int yeniNesne = 1;
int yenidenKullanilan = 4;

Thanks to the pool the allocation count drops and the game runs smoother.

Practice Report the pool saving

In a class named HavuzTakip, define an integer field named yeniNesne with the value 1 and an integer field named yenidenKullanilan with the value 4. In the Start method add these two values into an integer named toplam and print the text "Havuz tasarrufu: " joined with toplam using Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class HavuzTakip : MonoBehaviour
{
    // yeniNesne adli tam sayi alanini 1, yenidenKullanilan adli tam sayi alanini 4 degeriyle tanimla

    void Start()
    {
        // bu iki degeri toplayip toplam adli tam sayiya ata
        // "Havuz tasarrufu: " + toplam biciminde yazdir
    }
}

Sample solution

Player.cs
using UnityEngine;

public class HavuzTakip : MonoBehaviour
{
    int yeniNesne = 1;
    int yenidenKullanilan = 4;

    void Start()
    {
        int toplam = yeniNesne + yenidenKullanilan;
        Debug.Log("Havuz tasarrufu: " + toplam);
    }
}

Expected output

Havuz tasarrufu: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is object pooling used?

  • To soften the lights in the scene
  • To reduce new allocations and reuse objects Correct answer
  • To increase the number of code lines
  • To compile files faster

Explanation: A pool uses old objects instead of producing new ones, which lowers the allocation count.

2 Deactivate the object

Question
    gameObject.SetActive(____); // nesne yok edilmez, pasif yapilir
Answer
    gameObject.SetActive(false); // nesne yok edilmez, pasif yapilir

Explanation: SetActive(false) deactivates the object; the pooled object is set aside without being destroyed.

3 Pool terms

Term Meaning
Havuz (pool) The list where objects are reused
Yeniden kullanma Taking an old object instead of new
SetActive(false) Deactivating the object
Tahsis tasarrufu The reduced amount of allocation

All lessons in Expert