Almost every game nowadays requires multiple objects to spawn and disappear at a given time. Sure it’s possible to generate all of them when the player launches the game, but that is very inefficient, due to the resources needed to generate them, and inflexible, due to not being able to generate more when need to. That’s why it is important to learn how to spawn objects when you need to and destroy them when you’re done with them.
Generating Game Objects in Unity
Generating game objects is simply one line of code:
Instantiate is a method nested inside the Object class. By using Instantiate, the code will clone the original object (in this case, a game object) and return an exact clone that will populate on the Hierarchy.
Furthermore, there are a total of 4 overloads for the Instantiate method. You can:
- Attach to another Transform: Useful when you want keep all the clones nested within another game object on the Hierarchy
- Set to world or parent space: When attached to another object, you can set it to True if you want to use the world space or False when you want to use the position of the parent
- Set to a different location: Useful when you want to randomly generate a location of the clone and not the original
- Set to a different rotation: like location, useful when you want to randomly generate a different rotation for each clone generated.
Destroying a Game Object
Now with all these generated game objects in the scene, there must be a way to destroy them. Luckily there is, and like generating them, you only need one line to destroy them:
Like Instantiate, Destroy is also a method within the Object class and is straightforward: destroying the object that’s being passed through. Moreover, if you want a delay, you can also set a timer on when to destroy said object.
However, there are a few things to take note:
- The object is destroyed immediately the moment it’s called (or after the delay if defined). As a result, any code after Destroy will not be called.
- You can also destroy components like scripts and Rigidbodies too. If you still require the actual object to stay in the scene, you can specifically target the component. This way, the component is destroyed while leaving the object intact.