Instatiate & Destroy in Unity: a simple look at a clone’s life cycle
Game objects in a Unity scene are listed inside the Hierarchy window. These “objects”, whether empty or with game components, can be cloned. Instantiation is the creation of an object as an instance of a class; this is creating a clone from a prefab. Prefab game objects (prefabricated) are saved in the project window as an asset that may be cloned and have all clones respond to the changes done to the original prefab. A prefab may be imported from a package of assets or created in the hierarchy to be dragged and dropped into the project window.
One of the most common examples of a prefab is bullets, which in reality is the bullet prefab. Weapons tend to have 30-rounds magazines, all bullets being cloned from a specific prefab. There are many methods to manage prefabs cloning, some more efficient than others depending on the game’s optimal specifications.
Topics:
- Instantiate method
- Destroy method
The method Instantiate() can be implemented, best when the prefab already exists in the project window. The example below shows how to instantiate ten game objects, having each prefab 2 units apart from each other on the X coordinate.
The example below instantiates a Laser Shot prefab every time the Space Bar is pressed down. The Hierarchy window shows how quickly the clones are created.
void ShootLaser()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(_laserPrefab, transform.position + new Vector3(0,0.8f,0), Quaternion.identity);
}
}
There are many clones being created but none of them are destroyed; this can cause huge performance issues during Game Play.
The Destroy() method is very useful to get rid of objects that are no longer necessary. This method can also be used to remove a specific component or asset. For this case, the method is used inside a script that controls the laser shot behavior, where the laser is programmed to move in a certain direction, and to be destroyed after getting out of the screen, in this case 8 units on the Y axis.
public class Laser : MonoBehaviour
{
private float _laserSpeed = 9.5f;
void Update()
{
transform.Translate(Vector3.up * _laserSpeed* Time.deltaTime);
if(transform.position.y > 8)
{
Destroy(this.gameObject);
}
}
}
And as a result:
Conclusion
The Instantiate and Destroy methods are very simple and useful to quickly implement functionalities similar to shooting or spawning enemies. It’s simplicity may lead to performance issues as the game play expands and more features are implemented; exploring other topics like Object Pooling may lead to more performant solutions, depending on the specifications for each Game Manager.