Managing game objects
Whenever you have a script that instantiates objects, you must be aware of the life cycle of the object and possibly arrange to destroy it when it is no longer needed. You can destroy game objects, for example, after it is no longer visible in the scene, or after a specific life duration, or limit the scene to a maximum number of balls.
Destroying fallen objects
In our scene, we have a limited size ground plane and as balls hit one another, some will fall off the plane into oblivion. At that point, we can remove the fallen ball from the scene. Watch the Hierarchy
panel as new balls are instantiated. Note that some balls end up bouncing off the plane platform but remain in the Hierarchy
panel. We need to clean this up by adding a script that destroys the balls that are out of play, as follows:
- Select the
BouncyBall
prefab inProject Assets/Prefabs
- Navigate to
Add Component
|New Script
and name itDestroyBall
Here's a DestroyBall.cs
script, which will destroy the object...