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.

Under the newly created prefab folder we can see the laser prefab

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

Dropping a reference to our laser prefab into the player script.

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.

10 options provided when instantiating our laser

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:

quaternion.identity

We have filled in our method.

Now we have the logic entered we can test it in game;

The laser appears, but must be asleep because it is staying put.

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.

Finally we have a laser that moves.

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.

So many lasers. Where's the social distancing!?

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.

We could use time to destroy the laser but that logic might cause errors later.

What we can do now is create a condition that once the laser leaves the screen we then call our destroy function.

We made a logic check that will destroy the laser when I moves off camera.

Now we can test this in the game.

Mass creation and destruction.

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.

Unity developer with a love of learning all things programming.