Instantiating & Destroying Gameobjects in Unity

Objective: Adding and removing game objects from your game.

Being able to add and remove game objects is essential to any game, whether it be adding enemies for us to destroy or powerups to give us advantages against the enemy and removing objects when they are destroyed/collected or when they leave the scene. Unity provides methods for us to use to accomplish these tasks, they are:

Instantiate and Destroy methods

Instantiate:

This method creates a clone of the object original(prefab) and adds it to the scene. The very basic form of this method takes 3 parameters. The first is the original (game object) we want to have added to the scene. In most cases, we will be using a reference to a game object(prefab). This is illustrated below:

Game Object reference

The second parameter is the position, this is the position in space where you want to have the object placed. This is represented with a Vector3 also you can use the position of another game object. This is illustrated below:

Transform. position and Vector 3

The third parameter is the rotation, this is the initial orientation of the new object. This, for the most part, is represented by Quaternion.identity.

putting everything together: This will spawn the laserprefab at the position of the object doing the instantiate.

Instantiate method

Putting everything together, I have put the instantiate method inside an if statement to instantiate the laser when the spacebar is pressed.

Instantiate method for the laser
Instantiate laser

This covers the basic form of the Instantiate method. There are other arguments that can be used. If you would like to learn more you can search the online unity documentation for Instantiate().

Destroy:

This method removes the object from the scene. The destroy method has 2 parameters. The first parameter is obj, this is the game object to destroy. The second parameter is t, this is the amount of time to delay before destroying the object. the default for t is 0, which will destroy the object immediately.

Destroy Method Syntax

One reason to destroy an object is when the object leaves the scene view. I added a script to the laser, when the laser leaves the scene view I destroy the object.

Laser destroyed when leaving the scene

For more information on the Destroy method, you can search the online unity documentation for Destroy.

Happy Coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store