Game Development
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.
Exercise 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.
Show example solution
using UnityEngine;
public class HavuzTakip : MonoBehaviour
{
int yeniNesne = 1;
int yenidenKullanilan = 4;
void Start()
{
int toplam = yeniNesne + yenidenKullanilan;
Debug.Log("Havuz tasarrufu: " + toplam);
}
}
Test yourself
-
Why is object pooling used?
- To soften the lights in the scene
- To reduce new allocations and reuse objects
- To increase the number of code lines
- To compile files faster
Show answer
To reduce new allocations and reuse objects — A pool uses old objects instead of producing new ones, which lowers the allocation count.
-
Deactivate the object
gameObject.SetActive(____); // nesne yok edilmez, pasif yapilir
Show answer
gameObject.SetActive(false); // nesne yok edilmez, pasif yapilir
-
Pool terms
- 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
Next lesson: Asset bundle