Why Pool Objects
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 37 of 50.
A gun that fires 10 bullets a second for a minute calls Instantiate 600 times and Destroy 600 times. Each Instantiate copies the prefab with all its components and runs their Awake, OnEnable and Start. Each Destroy runs OnDisable and OnDestroy and leaves the object's memory behind as garbage. C#'s garbage collector frees that memory later, and its work lands on some frames and not on others, which shows as a stutter, worst on slower phones.
A pool keeps objects instead of destroying them. A spent bullet is switched off with SetActive(false) and goes back into the pool; the next shot takes one out and switches it on, and Instantiate runs only when the pool is empty. After the first few seconds of shooting, firing makes nothing new and leaves no garbage. On reuse, Awake and Start do not run again: they ran once, when the object was made. Whatever must start over on every use, such as a timer, health or a velocity, is reset in OnEnable or by the code that takes the object out.
Pooling pays for objects that are made and thrown away often: bullets, sparks, damage numbers, the enemies of a wave game. It does not pay for a boss that appears once or a menu that opens now and then. A pool holds memory for its inactive objects all the time, so it keeps a sensible number and lets the extra ones go.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types