How to be an all-powerful being — A quick guide to instantiation and destruction in Unity
What is Instantiation?
Instantiation is creating an instance or clone of an original object into our scene. Take a laser from a spaceship. This object gets created and “prefabbed” so we have an original object we can clone in our project files.
When we need to instantiate an object we generally need a reference to that object on our script.
Which requires the prefab object to be dropped into the refence holder
Then we can use the refence to “spawn” a clone of this object using the method “Instantiate”.
We get several options when instantiating an object but we are going to focus on our example of shooting a laser in this article so we only need to use 1.
We need to provide an object original, a position to spawn and a rotations as seen above.
We add our prefab in as the object original, add our current position and, as Unity handles rotation via quaternions, we use the following to provide a rotation of zero:
Now we have the logic entered we can test it in game;
We can now add a script to our laser to get it to move upwards. Check out the article on Player Input in Unity to see logic on how to do that if you are not sure.
Now we have our laser moving we may notice another issue. In our hierarchy we are filling up with laser clones which is not great for performance. At the moment the laser just travels on infinitely and continues to use system resources while it is active. What we need to do is destroy the object when it leaves the screen.
How to destroy an object?
The logic to destroy an object is quite simple. We use the “Destroy” method. The “Destroy” method has 2 options.
The first option, we pass in an object reference and then when the code runs the object is destroyed instantly.
The second option is to pass in a float for time, this will mean the object gets destroyed after this time has passed. We are just going to destroy our laser immediately within our function.
What we can do now is create a condition that once the laser leaves the screen we then call our destroy function.
Now we can test this in the game.
Now our laser has logic to be instantiated and destroyed and our hierarchy is being cleaned up when the lasers are no longer on camera.