Reducing the number of objects by destroying objects at death a time
Optimization principal 1: Minimize the number of active and enabled objects in a scene.
One way to reduce the number of active objects is to destroy objects when they are no longer needed. As soon as an object is no longer needed, we should destroy it; this saves both memory and processing resources since Unity no longer needs to send the object such messages as Update()
and FixedUpdate()
, or consider object collisions or physics and so on.
However, there may be times when we wish not to destroy an object immediately, but at some known point in the future. Examples might include after a sound has finished playing (see that recipe Waiting for audio to finish before auto-destructing object in Chapter 9, Playing and Manipulating Sounds), the player only has a certain time to collect a bonus object before it disappears, or perhaps an object displaying a message to the player should disappear after a certain time.
This recipe...